-1

The following code:Array.from({length: 5}, (v, i) => i);

returns the following array [0, 1, 2, 3, 4]

Are there any other conditions you can include in the curly braces? (for example to change the value of the initial element or the step of the sequence)

4
  • The second argument could be any function, it works just like array#map. Commented Jul 13, 2020 at 9:00
  • 1
    See e.g. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - the first argument is an array-like, which is why an object with a length prop works.
    – jonrsharpe
    Commented Jul 13, 2020 at 9:00
  • Yes, I went through that article but I haven't seen the {length: } feature before. I was wondering if it had a name and what the alternatives might be. Commented Jul 13, 2020 at 9:00
  • 5
    {length: 5} is not a "condition" it's an array-like that can be used to generate a new array of similar length. That's it. If you include a positive integer property which is within bounds (e.g., {0: "hello", 1: "world", length: 5} then you'd get that as the first parameter of the callback (v in this case).
    – VLAZ
    Commented Jul 13, 2020 at 9:01

1 Answer 1

1

Array.from takes an iterable or array-like value and makes a “real” Array from it.

In your example {length: 5} is an array-like object.

Example of iterable object which can also be passed to Array.from:

let range = {
  from: 1,
  to: 5,

  [Symbol.iterator]() {
    this.current = this.from;
    return this;
  },

  next() {
    if (this.current <= this.to) {
      return { done: false, value: this.current++ };
    } else {
      return { done: true };
    }
  }
};

for (let num of range) {
  alert(num); // 1, then 2, 3, 4, 5
}

For additional info please see:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.