<script>
// 浅拷贝对象
const obj = {
name: 'hello',
age: 14
}
// 1、Object.assign()
const newObj1 = Object.assign({}, obj);
newObj1.name = 'vite';
console.log(obj); // {name: 'hello', age: 14}
console.log(newObj1); // {name: 'vite', age: 14}
// 2、扩展运算符
const newObj2 = { ...obj };
newObj2.name = "ts";
console.log(obj); // {name: 'hello', age: 14}
console.log(newObj2); // {name: 'ts', age: 14}
// 浅拷贝数组
const arr = [1, 2, 3, 4];
// 1、[].concat()
const newArr1 = [].concat(arr);
newArr1[0] = 5;
console.log(arr); // [1, 2, 3, 4]
console.log(newArr1); // [5, 2, 3, 4]
// 2、扩展运算符
const newArr2 = [...arr];
newArr2[0] = 6;
console.log(arr); // [1, 2, 3, 4]
console.log(newArr2); // [6, 2, 3, 4]
</script>
20、js - 面试 - 浅拷贝
猜你喜欢
转载自blog.csdn.net/EchoLiner/article/details/131067827
今日推荐
周排行