简体   繁体   English

如何使用lodash js检查字符串是否存在于数组中?

[英]How to check whether string is present in array with lodash js?

My snippet looks something like this: 我的代码段看起来像这样:

let go = "hello";

let col =["12","hello","14","15"];

let f = _.some(col,go);

I want to check whether the go value is present in col TRUE/FALSE. 我想检查go值是否在col TRUE / FALSE中。 When I run this I get , f=false? 当我运行它时,得到f = false? How can I fix this or how to check the presence of a string in an array of strings (with lodash)? 如何解决此问题或如何检查字符串数组中是否存在字符串(使用lodash)?

Should work 应该管用

let go = "hello";

let col =["12","hello","14","15"];

let f = _.includes(col,go);

https://lodash.com/docs#includes https://lodash.com/docs#includes

With only javascript you can use indexOf . 只有JavaScript,您可以使用indexOf If it is present it will return the index of the element else -1 如果存在,它将返回元素的索引,否则为-1

 let go = "12"; let col = ["12", "hello", "14", "15"]; var isElemPresent = (col.indexOf(go) !== -1) ? true : false console.log(isElemPresent) 

It seems that You misunderstood what the last arguments of _.some is. 您似乎误解了_.some的最后一个参数。 You can't use it as a value for equality test, but You need to make one yourself like this: 您不能将其用作相等性测试的值,但您需要这样一个人:

let f = _.some(col, function(go) {return go === "hello"});

And here is working Fiddle for You. 这是为您工作的小提琴

Or alternatively you can use es6 magic and call includes directly from your array like this 或者,您也可以使用es6 magic,像这样直接从数组中调用包含

 let go = "hello"; let col =["12","hello","14","15"]; alert(col.includes(go)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM