此函数中 Array() 的上下文

Context of Array() in this function

  it("should know properties that are functions act like methods", function() {
    var meglomaniac = { 
      mastermind : "Brain", 
      henchman: "Pinky",
      battleCry: function(noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = meglomaniac.battleCry(4);
    expect('They are Pinky and the Brain Brain Brain Brain').toMatch(battleCry);
  });

这段代码(第 7 行)中 Array 的定义是什么?我查了一下,它看起来像是一个 Array.of() 命令,它生成一个长度为 n 的空数组,在本例中为 5?那么,假设这是正确的假设,为什么最终只有 4 个大脑输入?或者这个 array() 在做别的事情?

battleCry(4) 表示 Array(noOfBrains + 1) 的长度确实为 5:

[empty, empty empty, empty, empty]

但是当你 .join 这 5 个元素时,你只在 它们之间的空格中插入了一些东西 ,并且只有 4 个空格:

[empty, empty empty, empty, empty]
//     ^     ^      ^      ^

因此,您最终在结果字符串中出现了 4 次 this.mastermind

这段代码相当混乱。我非常喜欢 .repeat 之类的东西:

var meglomaniac = { 
  mastermind : " Brain", 
  henchman: "Pinky",
  battleCry: function(noOfBrains) {
    return `They are ${this.henchman} and the${this.mastermind.repeat(noOfBrains)}`
  }
};

var battleCry = meglomaniac.battleCry(4);
console.log(battleCry === 'They are Pinky and the Brain Brain Brain Brain');

Array 只是数组构造函数。它并没有什么特别的,它只是创建了一个数组,其中有一个 length 的参数(当传递一个数字时)。

通过使用 Array.fill().

,您可以避免手动将数组中的元素数加 1 来解决这个问题。
Array(4).fill("Brain").join(" ");   // have an array of 4 elements,
                                    // fill each vacant spot with "Brain"
                                    // and flatten it by separating elements
                                    // by a space
//Brain Brain Brain Brain

所以你的代码可以简化为:

Array(noOfBrains).fill(this.mastermind).join(" ");