Jin*_* DO 3 javascript arrays ecmascript-6 lodash
我有2个阵列
const arr1 = [[1,2],[3,4],[5,6]];
const arr2 = [1,2,3,4,5];
Run Code Online (Sandbox Code Playgroud)
我想得到这些数组中的具体元素来记录
有2种情况:
1 /
console.log(_.find(arr1,0,1));
console.log(_.find(arr2,0,1));
Run Code Online (Sandbox Code Playgroud)
它返回undefined与arr2
2 /
console.log(_.find(arr1[1],0,1));
Run Code Online (Sandbox Code Playgroud)
这个也回来了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]
Run Code Online (Sandbox Code Playgroud)
在以下情况下,您将传递一个Number作为第二个参数:
Lodash 需要一个作为它的第二个参数 是每次迭代调用.
_.find()function
作为第二个参数传入的函数接受三个参数:
value - 迭代当前值
index | key - 集合的数组或键的当前索引值
collection - 对迭代的集合的引用
您传递的是需要函数的索引值.
如果你想在arr1中获取第二个元素,你不需要lodash,但可以使用括号表示法和索引号直接访问:
arr1[1]
Run Code Online (Sandbox Code Playgroud)
如果你坚持使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1103 次 |
| 最近记录: |