ES6中(…)运算符
文章描述:
es6(…)运算符应用
合并数组
es5写法,使用concat
let arr1 = [1,2];
let arr2 = [5,6];
let newArr = [20];
newArr = newArr.concat(arr1).concat(arr2);
console.log(newArr)
[20, 1, 2, 5, 6]
es6写法
let arr1 = [1,2];
let arr2 = [5,6];
let arr3 = [20];
let newArr = [...arr3,...arr1,...arr2];
console.log(newArr)
[20, 1, 2, 5, 6]
合并对象
const user = {
name:'小坏蛋',
age:'20'
}
const userInfo = {
email:'123@qq.com',
address:'成都市'
}
const item = {...user,...userInfo}
console.log(item)
{name: ‘小坏蛋’, age: ’20’, email: ‘123@qq.com’, address: ‘成都市’}
数组增加新值
const arr1 = ['苹果','香蕉']
const arr2 = '草莓'
const arr = [...arr1,arr2]
console.log(arr)
[‘苹果’, ‘香蕉’, ‘草莓’]
对象增加新值
const user = {name:'小明',age:20}
const obj = {
...user,
email:'123@qq.com',
address:'四川省'
}
console.log(obj)
{name: ‘小明’, age: 20, email: ‘123@qq.com’, address: ‘四川省’}
将一个数组添加到另一个数组的尾部
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
//es5写法
Array.prototype.push.apply(arr1, arr2);
console.log(arr1)
[0, 1, 2, 3, 4, 5]
//es6写法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
console.log(arr1)
[0, 1, 2, 3, 4, 5]
将字符串转换成数组
// es5
let str = 'hello'
var arr = str.split('')
console.log(arr)
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
// es6
let str = 'hello'
var arr = [...str]
console.log(arr)
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
解构赋值
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }
let arr = [1,2,[1,2],3];
let arr2 = [...arr];
arr2.push(1);
console.log(arr);//[1,2,[1,2],3]
console.log(arr2);//[1,2,[1,2],3,1]
发布时间:2023/05/12
发表评论