【问题标题】:Lodash forEach Associative ArrayLodash forEach 关联数组
【发布时间】:2014-08-12 12:01:50
【问题描述】:

Lodash 中是否有用于关联数组的 forEach 循环?我发现称为“forEach”的函数仅适用于索引数组。例如,如果我有一个数组myArray,其值为[1, 2, 3],然后做

lodash.forEach(myArray, function(index) {
    console.log(index);
});

并运行函数(在Node),我得到了预期的结果:

1
2
3

但是,当我尝试使用关联数组时,它不起作用:

lodash = require('lodash');
myArray = [];
myArray['valOne'] = 1;
myArray['valTwo'] = 2;
myArray['valThree'] = 3;
lodash.forEach(myArray, function(index) {
    console.log('7');
});

正如您在Node 中运行它所看到的,即使回调函数包含数组元素以外的内容,它也不会触发。它似乎完全跳过了循环。

首先,为什么会发生这种情况?其次,Lodash 中是否包含另一个函数来解决这个问题,或者,如果没有,有没有办法使用forEach 函数来完成这个,而不需要更改过程中的原始数组?

【问题讨论】:

    标签: javascript arrays node.js foreach lodash


    【解决方案1】:
    myArray = [];
    myArray['valOne'] = 1;
    myArray['valTwo'] = 2;
    myArray['valThree'] = 3;
    lodash.forEach(myArray, function(index) {
        console.log('7');
    });
    

    关联数组只是一组键值对,它只不过是一个 Javascript 对象。 以上案例 - myArray.length === 0, 您只是向数组对象添加属性,而不是向实际数组添加任何值。

    而是像这样初始化你的 myArray 并使用 forIn 循环遍历

    var myArray = {};
    myArray['valOne'] = 1;
    myArray['valTwo'] = 2;
    myArray['valThree'] = 3;
    
    lodash.forIn(myArray, function(value, key) {
        console.log(key + " : " + value); 
    });
    

    或者只是

       var  myArray = {
        valOne  : 1,
        valTwo  : 2,
        valThree : 3
       };
    
       lodash.forIn(myArray, function(value, key) {
            console.log(key + " : " + value); 
        });
    

    更多关于对象作为关联数组here

    【讨论】:

      【解决方案2】:

      Lodash 具有用于此目的的函数 forOwn。在第二个数组中,如果你这样做了

      _.forOwn(myArray, function(index) {
          console.log(index);
      });
      

      你应该得到预期的结果。

      我仍然不确定为什么forEach 似乎跳过了第一个函数,但是我相信这可能与没有“长度”的数组有关。 JavaScript 数组的长度是它拥有的最高编号索引。例如,定义为 myOtherArray[999]="myValue" 的数组 myOtherArray 的长度为 1,000(因为数组是零索引的,这意味着它们从 0 开始,而不是 1),即使它没有其他值。这意味着没有编号索引或只有负索引的数组将没有length 属性。 Lodash 必须注意到这一点,而不是给数组一个 length 属性,可能会保持一致性和性能,因此不会呈现任何输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-09
        • 2015-11-09
        • 1970-01-01
        • 2015-06-01
        • 1970-01-01
        相关资源
        最近更新 更多