apply()
to compute the maximum value in an array:
var arr = [6, 89, 3, 45];We had to use
var maximus = Math.max.apply(null, arr); // returns 89
Math.max.apply(null, arr)
because Math.max(arr)
returns NaN
. Math.max()
expects comma-separated arguments, but not an array.
The spread operator makes this syntax much better to read and maintain.
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89
...arr
returns an unpacked array. In other words, it spreads the array.
However, the spread operator only works in-place, like in an argument to a function or in an array literal. The following code will not work:
const spreaded = ...arr; // will throw a syntax error
arr1
into another array arr2
using the spread operator.
arr2
is correct copy of arr1
.
testString: assert(arr2.every((v, i) => v === arr1[i]), 'arr2
is correct copy of arr1
.');
- text: ...
spread operator was used to duplicate arr1
.
testString: getUserInput => assert(getUserInput('index').match(/\[\s*...arr1\s*\]/g),'...
spread operator was used to duplicate arr1
.');
- text: arr2
remains unchanged when arr1
is changed.
testString: assert((arr1, arr2) => {arr1.push('JUN'); return arr2.length < arr1.length},'arr2
remains unchanged when arr1
is changed.');
```