javascript Lodash findIndex 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32137269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lodash findIndex not working
提问by yeouuu
Why is lodash returning -1 here? It's clearly in there?
为什么 lodash 在这里返回 -1?明明在里面?
Ignores = ['load', 'test', 'ok'];
alert(_.findIndex(Ignores, 'ok') );
回答by tgkokk
That's because findIndex()takes as parameters an array and a predicate, a function that returns a boolean value based on some condition.
这是因为findIndex()将数组和谓词作为参数,谓词是一个基于某些条件返回布尔值的函数。
Assuming you are searching for needle
in haystack
, you can achieve what you want with normal JavaScript:
假设您正在搜索needle
in haystack
,您可以使用普通的 JavaScript 实现您想要的:
alert(haystack.indexOf(needle));
You can use _.indexOf
(from @Juhana):
您可以使用_.indexOf
(来自@Juhana):
alert(_.indexOf(haystack, needle))
You can do it with _.findIndex
too:
你也可以这样做_.findIndex
:
alert(_.findIndex(haystack, function(x) { return x === needle; }));
or:
或者:
alert(_.findIndex(haystack, _(needle).isEqual));
回答by Sachin Mishra
The loadash _.findIndexis quite work in different order of the JSON structure.If you would like to get the index of the array object based upon the nested structure.The lodash has provided the same special way to do it.
该loadash _.findIndex是不同的顺序JSON structure.If你想获得基于嵌套structure.The lodash数组对象的指数相当的工作提供了相同的特殊的方式来做到这一点。
Let assume if your JSON structure is like below mentioned pattern. lstMainArray: [{searhName:'Abc1',searchName:'Abc2'}]
假设您的 JSON 结构是否类似于下面提到的模式。lstMainArray: [{searhName:'Abc1',searchName:'Abc2'}]
and you would like to search from nested JSNO such as :
并且您想从嵌套的 JSNO 中进行搜索,例如:
searchObject : { searchField:{ searchName:'Abc1' } }
searchObject : { searchField:{ searchName:'Abc1' } }
you can make the below syntax to use it.
您可以使用以下语法来使用它。
_.findIndex(lstMainArray,['searchField.searchName','Abc1']);
_.findIndex(lstMainArray,['searchField.searchName','Abc1']);