一、JSON.stringify and JSON.parse
現使用 JSON.stringify 將 Object 對象轉化成基本類型 String,再使用 JSON.parse 將 String 轉換成 Object。如
var a = { name: '張三' }
var b = JSON.parse( JSON.stringify(a) )
缺點:不能拷貝 undefined、Function、RegExp 等類型
二、Object.assign
var b = Object.assign({}, a)
缺點:只拷貝了第一層
三、遞歸拷貝
function deepClone (obj) {
let result = {};
if (!obj || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
result = []
obj.forEach(item => {
result.push( deepClone(item) )
})
} else {
Object.keys(obj).forEach(key => {
result[key] = deepClone(obj[key])
})
}
return result;
}