This article brings you an introduction to the expansion symbols in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The expansion symbol is really a very useful thing. I often use it for string splitting, array merging, array copying, object merging, and object copying.
...iterableObj
This is to expand the parameters when the function is called, which is different from the remaining parameters. The remaining parameters are in Use in function declaration
myFunction(...iterableObj);
Case
function add(a, b){ return a + b } add(...[1,2]) // 相当于 add(1,2) -> 3
Can be used for array merging
[...[1,2,3],4] // 相当于[1,2,3].push(4) -> [1,2,3,4] [...'1234'] // 相当于 '1234'.split("")
Can be used for objects Merge, object copy
{...{name:1},age:2} // 相当于 Objeact.assign({},{name:1},{age:2}) -> {name:1,age:2} {...{name:1}} // 相当于 Object.assign({},{name:1}) -> {name:1}
String/array expansion
Source code
[...'1234']
After translation
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } [].concat(_toConsumableArray('1234'));
Object expansion
Source code
let a={...{name:1}}
After translation
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var a = _extends({ name: 1 });
The above is the detailed content of Introduction to expansion symbols in ES6. For more information, please follow other related articles on the PHP Chinese website!