Home >Web Front-end >JS Tutorial >Introduction to expansion symbols in ES6

Introduction to expansion symbols in ES6

不言
不言forward
2018-11-14 15:41:543598browse

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.

Overview

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.

0x001 Syntax

...iterableObj

0x002 Parameter expansion when the function is called

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

Array declaration expansion

Can be used for array merging

[...[1,2,3],4] // 相当于[1,2,3].push(4) -> [1,2,3,4]
[...'1234'] // 相当于 '1234'.split("")

Object expansion

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}

babel translation

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!

Statement:
This article is reproduced at:https://segmentfault.com/a/1190000016977223. If there is any infringement, please contact admin@php.cn delete