【扩展运算符应用】
数组中
1、遍历数组
var arr = [1, 2, 3, 4];
console.log(...arr);
2、可以当做数组的参数
var arr = [1, 2, 3, 4];
var numArr = ["a", ...arr, "b"];
console.log(numArr);
3、深拷贝 传值
var arr = [1, 2, 3, 4];
var arrA = [...arr];
console.log(arrA);
arrA.unshift(0);
console.log(arrA);
console.log(arr);
4、可以作为函数中的参数
var arr = [1, 2, 3, 4];
function fn(x, ...y) {
console.log(x);
console.log(...y);
}
fn(...arr);
5、可以和解构赋值连用
var arr = [1,2,3,4]
let [a, ...b] = arr
console.log(a);
console.log(b);
6、可以将伪数组,转换成真正的数组
var str = "我们真好";
console.log(Array.from(str));
console.log([...str]);
对象中
1、对象的遍历
var obj = {
name: "name",
age: 18,
sex: "男",
};
console.log({ ...obj});
也可以添加属性,会覆盖
var obj = {
name: "name",
age: 18,
sex: "男",
};
console.log({ ...obj, name: "zs", age: 20 });
</script>
2、对象的合并
var obj_1 = {
a: 1,
b: 2,
};
var obj_2 = {
b: 3,
...obj_1,
};
console.log(obj_2);
3、解构赋值
let { a, b, ...c } = { a: 1, b: 2, c: 3, d: 4, e: 5 };
console.log(a); //1
console.log(b); //2
console.log(c); //{c: 3, d:4, e: 5}
4、深拷贝
let obj_1={sty:'123',num:123}
let obj_2={...obj_1}
obj_2.number = 100
console.log(obj_1)
console.log(obj_2)