简体   繁体   中英

In this excerpt from javascript koans, what is the Array(foo+1) all about?

The koan is below. In my lessons, I've never seen the word "Array" just stuck into code like that. Any examples elsewhere that I can study?

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(FILL_ME_IN).toMatch(battleCry);
});

It should know properties that are functions act like methods. It is damaging your karma.

Expected 'Fill this value in' to match 'They are Pinky and the Brain Brain Brain Brain'.

So, Array(noOfBrains + 1) creates a new array of length five (well, given that noOfBrains is passed in as 4), in which every element is undefined:

[undefined, undefined, undefined, undefined, undefined]

Then, the join operation takes a string (" Brain"), and places a copy of it between each element of the array. (A more common use of join is something like array.join(", ") which comma-separates an array)

So we essentially have:

undefined + " Brain" + undefined + " Brain" + undefined + " Brain"+ undefined + " Brain" + undefined

Which becomes " Brain Brain Brain Brain", since the undefined's are ignored by join.

According to ECMAScript 15.4.1 , Array(...) acts just like new Array(...) :

When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(...) is equivalent to the object creation expression new Array(...) with the same arguments.

According to ES 15.4.2.2 , the single-argument form new Array(len) creates an empty array with the length property set to the value of the argument. So, Array(noOfBrains + 1) creates an empty array of size noOfBrains + 1 .

According to ES 15.4.4.5 , .join(separator) loops over the array for the value of the array's length (step 10). It builds a string by concatenating values from the array, joined by the separator value passed as an argument to join . According to step 8 and step 10.c, undefined array values are rendered as the empty string by .join .

Since the array you just initialized is empty, all of its values are undefined . Therefore, .join joins a list of the empty strings with the separator string " Brain ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM