mhahaha / js-snippets

Daily JS Snippets
0 stars 0 forks source link

JS对象深拷贝 @method deepClone #1

Open mhahaha opened 5 years ago

mhahaha commented 5 years ago
/**
 * 对象深拷贝
 * 
 * @method deepClone
 * @param {Object|Array} obj 克隆对象
 * 
 * @returns {Object|Array} 返回拷贝生成的新对象
 */
function deepClone (obj) {

    if (typeof obj !== 'object') {
        return;
    }

    let isArray = Array.isArray(obj);
    let copyResult = isArray ? [] : {};

    for (let i in obj) {
        let item = obj[i];
        let isObject = typeof item === 'object';

        copyResult[i] = isObject ? this.deepClone(item) : item;
    }

    return copyResult;
}
mhahaha commented 5 years ago

JSON.parse(JSON.stringify(obj)) 会过滤掉拷贝对象内 Function 类型的字段

let obj = {
    name: 'zhangsan',
    age: 18,
    say: word => `say ${word} ...`
}

console.log(JSON.parse(JSON.stringify(obj)))

image