浅拷贝
let res = Object.assign({}, sourceObj)
let res = Object.create(sourceObj)
lodash
var objects = [{ 'a': 1 }, { 'b': 2 }];
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true
原生js
var obj = {
name: '张三',
age: 23,
}
var result = {}
for (let key in obj) {
result[key] = obj[key];
}
console.log(result);
深拷贝
const result = JSON.parse(JSON.stringify(obj1))
lodash
let objects = [{ 'a': 1 }, { 'b': 2 }];
let deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]); // false
原生js
var obj = {
name: '张三',
age: 23,
child: {
name: '李四',
age: 14
}
}
function copy(obj) {
const tempObj = obj instanceof Array ? [] : {};
for (let key in obj) {
// if (obj.hasOwnProperty(key)) { // 应该加这一行,防止继承属性
// function可以指向同一个
tempObj[key] = typeof obj[key] === 'object' ? copy(obj[key]) : obj[key];
}
return tempObj;
}
console.log(copy(obj))
typeof的返回值
js共有6种数据类型:
(基本类型5种)number、string、boolean、undefined、null
(引用类型1种) object
typeof检测返回6种:
number、string、boolean、undefined
object、function
对象的属性合并
import _ from 'lodash'
const result = _.merge(obj1, obj2)