官术网_书友最值得收藏!

Spread

The spread operator (see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator) lets you expand an expression in places where you would otherwise require multiple arguments, elements, or variables. For example, you can replace arguments in a function call:

const x = [1, 2, 3];
function sum3(a, b, c) {
return a + b + c;
}
const y = sum3(...x); // equivalent to sum3(1,2,3)
console.log(y); // 6

You can also create or join arrays:

const f = [1, 2, 3];
const g = [4, ...f, 5]; // [4,1,2,3,5]
const h = [...f, ...g]; // [1,2,3,4,1,2,3,5]

It works with objects too:

const p = { some: 3, data: 5 };
const q = { more: 8, ...p }; // { more:8, some:3, data:5 }

You can also use it to work with functions that expect separate parameters, instead of an array. Common examples of this would be Math.min() and Math.max():

const numbers = [2, 2, 9, 6, 0, 1, 2, 4, 5, 6];
const minA = Math.min(...numbers); // 0

const maxArray = arr => Math.max(...arr);
const maxA = maxArray(numbers); // 9

You can also write the following equation. The .apply() method requires an array of arguments, but .call() expects inpidual arguments:

someFn.apply(thisArg, someArray) === someFn.call(thisArg, ...someArray);

If you have problems remembering what arguments are required by .apply() and .call(), this mnemonic may help: A is for array, and C is for comma. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call for more information.

Using the spread operator helps write shorter, more concise code, and we will be taking advantage of it.

主站蜘蛛池模板: 枣强县| 葫芦岛市| 锦州市| 阳谷县| 威远县| 合作市| 新源县| 合阳县| 祁连县| 柳州市| 东乡县| 勃利县| 易门县| 晋江市| 满城县| 通榆县| 芜湖市| 新蔡县| 安远县| 东城区| 铜川市| 阳江市| 阿克| 崇信县| 英超| 靖江市| 兴安盟| 彝良县| 新余市| 新化县| 中江县| 巴中市| 清原| 耿马| 马公市| 承德市| 民和| 会昌县| 施秉县| 扎囊县| 聂荣县|