我想遍历一个数组并获取它的关键和值。这就是我正在做的,但我没有得到任何输出。我做错了什么?
let regexes = [];
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.each(regexes, function(regex, key) {
console.log(regex, key);
});
答案 0 :(得分:1)
_.each
遍历数组的索引。您正在向数组对象添加非数字属性。您的数组为空,并且未执行_.each
回调。您似乎想要使用常规对象({}
)而不是数组:
let regexes = {};
现在_.each
应该遍历对象拥有(使用hasOwnProperty
方法)属性。
答案 1 :(得分:1)
您正在使用数组并向其添加一个无效的属性。使用它的对象
let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.each(regexes, function(regex, key) {
console.log(regex, key);
});
答案 2 :(得分:0)
您正在为数组分配属性。 Lodash试图遍历数组的数字索引,但没有。将数组更改为对象,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);
});