对象
使用变量作为对象的key
const name = 'name'
const obj = {
[name]:'t',
}
深拷贝
- 无function, undefined or NaN 值的情况
如果你的对象包含 function, undefined or NaN 值的话,JSON.parse(JSON.stringify(obj)) 就不会有效。因为当你 JSON.stringify 对象的时候,包含 function, undefined or NaN 值的属性会从对象中移除。因此,当你的对象只包含字符串和数字值时,可以使用JSON.parse(JSON.stringify(obj))
let obj = {x: 20, y: {z: 30}};
// Longhand
const makeDeepClone = (obj) => {
let newObject = {};
Object.keys(obj).map(key => {
if(typeof obj[key] === 'object'){
newObject[key] = makeDeepClone(obj[key]);
} else {
newObject[key] = obj[key];
}
});
return newObject;
}
const cloneObj = makeDeepClone(obj);
//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));
//Shorthand for single level object
let obj = {x: 20, y: 'hello'};
const cloneObj = {...obj};
对象遍历
entries
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
values
for (const item of Object.values(object1)) {
console.log(item);
}
keys
for (const item of Object.keys(object1)) {
console.log(`key: ${key}`);
}