JavaScript 展开语法(三个点 ...)

JavaScript About 2,357 words

展开语法

三个点...

合并数组

注意:合并后的数组是新对象,不同的地址值。

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
var arr3 = [...arr1, ...arr2];
// [0, 1, 2, 3, 4, 5]
console.log(arr3)

对象合并

合并不同的属性到同一个新对象中。

var obj1 = {name:'chuichui'}
var obj2 = {height:176}
var mergeObj = {...obj1,...obj2}
// mergeObj {name: 'chuichui', height: 176}
console.log("mergeObj", mergeObj)

对象属性合并

{...editor, name: 'xyz'}:使用name: 'xyz'替换editor中的name属性,合并生成新对象。

{name: 'abc', ...editor}:将editor中的name属性替换name: 'abc'属性,合并生产新对象。

const editor = {
    id: '1688',
    name: 'handome_boy',
    age: 18,
    male: 1
}

var v1 = {...editor, name: 'xyz'}
var v2 = {name: 'abc', ...editor}

// {id: '1688', name: 'xyz', age: 18, male: 1}
console.log("v1", v1)
// {name: 'handome_boy', id: '1688', age: 18, male: 1}
console.log("v2", v2)

解构数组

var number = [1,2,3,4,5,6]
// 1 2 3 4 5 6
console.log(...number)

解构字符串

var str = 'hello'
// h e l l o
console.log(...str)
// ['h', 'e', 'l', 'l', 'o']
console.log([...str])

分组解构

const [main, ...rest1] = labels:将labels数组中第0个元素赋值给main变量,...rest1labels数组中剩余元素赋值给rest1变量。

const labels = ['javascript', 'ES5', 'ES6', 'Vue.js'];
const [main, ...rest1] = labels;
// javascript
console.log(main);
// ['ES5', 'ES6', 'Vue.js']
console.log(rest1);

const {id, ...rest2} = editor:将editor中的id字段解构出来,单独赋值给id这个变量;...rest2editor中剩余属性赋值给rest2变量。

const editor = {
    id: '1688',
    name: 'handome_boy',
    age: 18,
    male: 1
}

const {id, ...rest2} = editor;
// 1688
console.log(id);
// {name: 'handome_boy', age: 18, male: 1}
console.log(rest2);

const {name, ...rest3} = editor;
// handome_boy
console.log(name);
// {id: '1688', age: 18, male: 1}
console.log(rest3);

const {nonExisted, ...rest4} = editor;
// undefined
console.log(nonExisted);
// {id: '1688', name: 'handome_boy', age: 18, male: 1}
console.log(rest4);

对象引用

引用对象的地址值,改变了副本对象的属性,原始对象的属性也会变更。

// 对象(地址的引用)
var man = {name: 'chuichui', height: 176}
// {name: 'chuichui', height: 176}
console.log(man)
// {name: 'chuichui', height: 176}
console.log({...man})
man.name = 'xxx'
// {name: 'xxx', height: 176}
console.log(man)
// {name: 'xxx', height: 176}
console.log({...man})

函数传参

// 函数传参
function f1(x, y, z) {
}

var args1 = [1, 2, 3]
f1(...args1)

function f2(v, w, x, y, z) {
}

var args2 = [2, 3]
f2(1, ...args2, 4, ...[5])

参考

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Views: 1,674 · Posted: 2022-07-06

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh