我的代码片段大致如下:
let go = "hello";
let col =["12","hello","14","15"];
let f = _.some(col,go);
我想检查go值是否存在于TRUE/FALSE列中。 当我运行此命令时,我得到了" f=false?"的输出。如何解决这个问题或者如何使用lodash检查一个字符串在一个字符串数组中的存在?
我的代码片段大致如下:
let go = "hello";
let col =["12","hello","14","15"];
let f = _.some(col,go);
我想检查go值是否存在于TRUE/FALSE列中。 当我运行此命令时,我得到了" f=false?"的输出。如何解决这个问题或者如何使用lodash检查一个字符串在一个字符串数组中的存在?
应该正常工作
let go = "hello";
let col =["12","hello","14","15"];
let f = _.includes(col,go);
只需使用 JavaScript,您就可以使用indexOf
。如果存在元素,则返回该元素的索引,否则返回-1。
let go = "12";
let col = ["12", "hello", "14", "15"];
var isElemPresent = (col.indexOf(go) !== -1) ? true : false
console.log(isElemPresent)
=== 1
。这会使得对于 '12'
、'14'
和 '15'
都返回 false
。 - Philcol.indexOf('12')
returns 0
which means it certainly is present. If col
contains "hello"
at position #3, this will return false
even though "hello"
is certainly present. Naming your variable isPresent
does not fit with what your code is doing. If you want it to be completely accurate, you should name it isHelloPresentAtExactlyTheSecondIndex
- Phil看起来您误解了_.some
的最后一个参数。您不能将其用作相等性测试的值,而是需要自己创建一个,如下所示:
let f = _.some(col, function(go) {return go === "hello"});
这里有一个可用的Fiddle。
或者,您可以使用es6魔法并直接从数组中调用includes,如下所示:
let go = "hello";
let col =["12","hello","14","15"];
alert(col.includes(go))