【问题标题】:lodash find array in array returns undefinedlodash 在数组中查找数组返回未定义
【发布时间】:2017-04-02 03:40:34
【问题描述】:

我有 2 个数组

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));

它返回undefinedarr2
2/

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]

【问题讨论】:

  • 第二种情况和第一种情况的第一种是一样的吗?两种情况都返回[1, 2]
  • 对不起,我错过了一些东西。我刚刚更新了
  • 你想做什么?意思是_.find(arr2,0,1),你在arr2中寻找0,起始索引为1,显然是undefinedlodash.com/docs/4.16.6#find
  • @Fahad 他不是在arr2 中寻找00 是真假测试。该函数在找到可接受的元素后立即返回,并且不会遍历整个列表。
  • 我刚刚更新了一点。你能检查一下吗?

标签: javascript arrays ecmascript-6 lodash


【解决方案1】:

在以下情况下,您将传入一个数字作为第二个参数:

Lodash _.find() 期望 function 作为其第二个参数 每次迭代都会调用。

作为第二个参数传入的函数接受三个参数:

  • 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

【讨论】:

  • 其实我认为索引排在最后lodash.com/docs/4.17.2#find
  • Not 作为_.find()的第二个参数传递给函数的参数
  • 速记怎么写?
  • 您可以使用箭头函数并省略集合参数以使事情更紧凑。如果您觉得我的回答对您有所帮助,那么将其标记为已接受的答案将不胜感激。
猜你喜欢
  • 2019-06-14
  • 2016-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
相关资源
最近更新 更多