Home > Web Front-end > JS Tutorial > body text

Introduction to expansion symbols in ES6

不言
Release: 2018-11-14 15:41:54
forward
3554 people have browsed it

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
Copy after login

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);
Copy after login

Case

function add(a, b){
    return a + b
}
add(...[1,2]) // 相当于 add(1,2) -> 3
Copy after login

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("")
Copy after login

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}
Copy after login

babel translation

String/array expansion

Source code

[...'1234']
Copy after login

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'));
Copy after login

Object expansion

Source code

let a={...{name:1}}
Copy after login

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 });
Copy after login

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!

Related labels:
source:https://segmentfault.com/a/1190000016977223
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template