- Mastering JavaScript Functional Programming
- Federico Kereki
- 255字
- 2021-07-02 22:41:07
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.
- Facebook Application Development with Graph API Cookbook
- 大學計算機基礎(第三版)
- 自己動手寫搜索引擎
- Learning Bayesian Models with R
- 大學計算機基礎(第2版)(微課版)
- Spring Boot企業級項目開發實戰
- INSTANT Adobe Edge Inspect Starter
- Angular應用程序開發指南
- Mudbox 2013 Cookbook
- Web前端測試與集成:Jasmine/Selenium/Protractor/Jenkins的最佳實踐
- Python數據可視化之matplotlib實踐
- Developer,Advocate!
- Python全棧開發:數據分析
- C語言從入門到精通(微視頻精編版)
- Learning C# by Developing Games with Unity 3D Beginner's Guide