通过每个下划线获取数组的键和值

get key and value of array via underscore each

我想遍历一个数组并获取它的键和值。这就是我正在做的,但我没有得到任何输出。我做错了什么?

let regexes = [];
regexes['some.thing'] = /([^.]+)[.\s]*/g;

_.each(regexes, function(regex, key) {
    console.log(regex, key);
});

_.each 遍历数组的索引。您正在向数组对象添加 非数字 属性。您的数组为空,_.each 回调未执行。您似乎想使用常规对象 ({}) 而不是数组:

let regexes = {};

现在 _.each 应该遍历对象 own(通过使用 hasOwnProperty 方法)属性。

您正在使用数组并向其中添加一个无效的 属性。请为其使用对象

let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;

_.each(regexes, function(regex, key) {
    console.log(regex, key);
});

您正在将 属性 分配给数组。 Lodash 正在尝试遍历数组的数字索引,但有 none。将数组更改为对象,Lodash 将遍历其可枚举属性:

let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;

_.forEach(regexes, function(regex, key) {
    console.log(regex, key);
});

或者,如果需要使用数组,只需将值压入其中即可:

let regexes = [];
regexes.push(/([^.]+)[.\s]*/g);

_.forEach(regexes, function(regex, i) {
    console.log(regex, i);
});