JavaScript Array filter()方法真的不改变原始数组吗?

时间:2016-12-28 04:07:16

标签: javascript

我知道filter()方法不会改变原始数组。 但是在下面的代码中,看起来它已被更改......

为什么newArray的尺寸(var)发生了变化? 如果filter()方法在这种情况下无关紧要,wordObj何时将它的值赋给newArray?

https://jsfiddle.net/s7mL1wtx/2/

function wordFrequency(words) {
  // size == frequency
  var newArray = [];
  var wordObj = [];
  words.forEach(function(word) {
    wordObj = newArray.filter(function(o) {
      return o.text == word;
    });
    if (wordObj.length) {
      console.log(word);
      console.log("=====");
      console.log(newArray);
      wordObj[0].size += 1;
    } else {
      newArray.push({
        text: word,
        size: 1
      });
    }
  });
  return newArray;
};

console.log(wordFrequency(["a", "b", "c", "c", "a", "a"]))

0 个答案:

没有答案