3019/03/05数组
深拷贝,简单的使用即是用 被封装好的,能够直接用于深拷贝的方法有:bash
... 扩展运算符
JSON.parse(JSON.stringify(source))
复制代码
可是用js代码去实现呢?ui
首先就是会想到遍历,去遍历数组,或者是对象。spa
想到遍历就会想到for 循环。prototype
for ... of 或者 for ... in 均可以实现,区别是 for ... of 能够由 break, throw 或return终止code
const deepClone = obj => {
const newObj = (Array.isArray(obj) ? [] : {}) // 判断是否是数组
for (const [k,v] of Object.entries(obj)) { // 将数组或者对象变为具备键值对的数组
//newObj[k] = v // 浅拷贝 将对象属性里面的值赋值给新对象
newObj[K] = (typeof v === 'object') ? deepClone(v) : v //深拷贝 (若是对象/数组里面的值仍是对象,则递归,再进行克隆)
}
return newObj
}
// 数组
let arr = [1,2,3]
//test1
let arr2 = deepClone(arr);
console.log(arr2,arr) // [1,2,3] [1,2,3]
//test2
let arr3 = deepClone(arr);
arr3[1] = 10;
console.log(arr3,arr) // [1,2,3] [1,2,3]
//对象
let people = {
name: {
firstName: 'wang',
lastName: 'huihui'
}
}
let someone = deepClone(people)
someone.name.lastName = 'test'
console.log(ArrObject2, ArrayOnject) // {name: {firstName: 'wang', lastName: 'huihui'} } {name: {firstName: 'wang', lastName: 'test'} }
复制代码
const deepClone = obj => {
const newObj = (Array.isArray(obj) ? [] : {})
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) { // 判断obj对象得原型链里面是否有key属性
newObj[key] = (typeof obj[key] === 'object') ? deepClone(obj[key]) : obj[key] /// 若是对象里面的属性仍是一个对象,则递归继续拷贝,将对象里面属性的值赋值给新的属性
}
}
return newObj
}
// 数组
let arr = [1,2,3]
//test1
let arr2 = deepClone(arr);
console.log(arr2,arr) // [1,2,3] [1,2,3]
//test2
let arr3 = deepClone(arr);
arr3[1] = 10;
console.log(arr3,arr) // [1,2,3] [1,2,3]
//对象
let people = {
name: {
firstName: 'wang',
lastName: 'huihui'
}
}
let someone = deepClone(people)
someone.name.lastName = 'test'
someone.name[lastName] = 'test' // 两个式子是同样的
console.log(ArrObject2, ArrayOnject) // {name: {firstName: 'wang', lastName: 'huihui'} } {name: {firstName: 'wang', lastName: 'test'} }
复制代码
方法介绍:对象
Object.prototype.hasOwnProperty.call() 会返回一个==布尔值==去判断对象自身属性中是否具备指定的属性 (重点查看 MDN)递归
Object.entries()返回一个给定对象自身可枚举属性的==键值对数组==,其排列顺序是于for..in 循环遍历改对象返回的顺序是一致的(for in 也枚举原型链中的属性)原型链
为了简便,最好能使用三元运算符去节省必定的代码!!!!!原型
则简单的浅拷贝:
///浅拷贝一个对象,或者数组
copyObject = (oldObj) => {
const newObj = {} // []
for (let k in oldObj) {
newObj[k] = oldObj[k]
}
}
或者使用 OBject.assign()
复制代码