Lodash中的查找数组在另一个数组中返回undefined。

3

我有两个数组

const arr1 = [[1,2],[3,4],[5,6]];
const arr2 = [1,2,3,4,5];

我希望获取这些数组中的特定元素进行记录。
有两种情况:
1/

console.log(_.find(arr1,0,1));
console.log(_.find(arr2,0,1));

当使用 arr2 时,it 返回 undefined

console.log(_.find(arr1[1],0,1));

这个代码也返回 undefined
有人可以告诉我我错过了什么吗?

编辑
对于 console.log(_.find(arr1,0,1));,我和 @Mr.7 得到了2个不同的结果:在 Chrome 控制台上我得到的结果是 [3,4] 但在 jsfiddle 上是 [1,2] 这与 Mr.7 相同。而且我已经注意到这个 _.find 中的一些奇怪之处。
以下是我的代码:

import _ from 'lodash';

const arr1 = [[1,2],[3,4],[5,6]];
const arr2 = [1,2,3,4,5];
const arr3 = [[0,2],[3,4],[5,6]];

console.log(_.find(arr1,1,1));//[3,4]
console.log(_.find(arr1,0,1));//[3,4]
console.log(_.find(arr2,2));//undefined
console.log(_.find(arr1,0));//[1,2]

console.log(_.find(arr3,0));//[3,4]
console.log(_.find(arr1,1));//[1,2]

你想做什么?通过 _.find(arr2,0,1) 这个函数,你在查找从索引 1 开始的数组 arr2 中的 0,但是很明显这个值是 undefined。了解更多请参考 https://lodash.com/docs/4.16.6#find。 - Fahad Khan
好的,明白了。期望的日志是什么? - Fahad Khan
@Mr.7 console.log(_.find(arr1,0,1)); 对我来说返回了[3,4],而且无论是0还是1,它们都返回相同的结果。 - Jin DO
1
我刚刚更新了一点,你能请检查一下吗? - Jin DO
@Pineda,如果我想从数组中获取第2个元素,你有什么建议? - Jin DO
显示剩余22条评论
1个回答

5
当您使用Lodash的_.find()函数时,它期望一个函数作为第二个参数,并在每次迭代时调用该函数。而您却将一个数字作为第二个参数传入。
作为第二个参数传入的函数接受三个参数:
- value - 当前正在迭代的值 - index|key - 数组的当前索引值或集合的键 - collection - 正在迭代的集合的引用
您传递了索引值,但实际上需要传递一个函数。
如果您想要获取arr1中的第二个元素,则不需要使用Lodash,可以直接使用方括号表示法和索引号进行访问。
arr1[1]

如果您坚持使用lodash,可以按照以下方式获取arr1的第二个元素(尽管为什么您更喜欢这种方法是值得怀疑的):
_.find(
     arr1,               // array to iterate over
     function(value, index, collection){   // the FUNCTION to use over each iteration
       if(index ===1)console.log(value)    // is the element at position 2?
     }, 
     1                   // the index of the array to start iterating from
   );                    // since you are looking for the element at position 2,
                         // this value 1 is passed, although with this set-up
                         // omitting won't break it but it would just be less efficient

实际上,我认为索引是最后一个参数。https://lodash.com/docs/4.17.2#find - Jin DO
不要将第二个参数作为传递给函数的参数来使用,这是与函数_.find()相关的编程内容。 - Pineda
你怎么用速记方式做这件事? - Jin DO
您可以使用箭头函数并省略集合参数以使代码更加简洁。如果您认为我的回答对您有帮助,那么将其标记为接受的答案将不胜感激。 - Pineda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接