用非数字作为key,就不会把“1” 排在最前面了
let codes = {
"+49": "Germany",
"+41": "Switzerland",
"+44": "Great Britain",
// ..,
"+1": "USA"
};
for (let code in codes) {
alert( +code ); // 49, 41, 44, 1
}
方法1:
const isEmpty = (obj) => {
for (let key in obj) {
return false
}
return true
}
方法2:
const isEmpty = (obj) => JSON.stringify(obj) === '{}'
方法3:
const isEmpty = (obj) => Object.keys(obj).length === 0
即,当对象属性为基本类型时,可以用如下方法进行对象拷贝;一旦含有引用类型属性时,下面的方法将失效。
const obj = {
"type": "1",
"title": "Criss",
"phone": "+86-10-84556681",
}
const obj2={}
Object.assign(obj2, obj)
或缩写
let clone = Object.assign({}, obj);
let clone =JSON.parse(JSON.stringify(obj))
不会拷贝: function、属性值为undefined、
属性值变为null: 属性值为-Infinity、属性值为Infinity、属性值为NaN
或
使用 lodash 库的 _.cloneDeep(obj)。
const obj = {
"title": "Criss",
fun:()=>{
console.log(this.title)
}
}
const obj = {
"title": "Criss",
fun(){
console.log(this.title)
}
}
user.address && user.address.street && user.address.street.name
user.address?.street?.name
?
对其前面的属性进行可选性校验,第一级写了不起作用,所以不用写
obj.method?.()
obj下有方法method才执行
vue 举例
title() {
return this.list?.[0]?.['title'];
},
const { log } = console
const user = {
id:1,
}
let id = Symbol("id");
let id2 = Symbol("id");
user[id]=2
user['id']=3
user[id2]=4
log(user)// { id: 3, [Symbol(id)]: 2, [Symbol(id)]: 4 }
let id = Symbol("id");
let user = {
[id]: 123,
name:'1111'
};
for (let key in user) {
log(key)
}
// name ,忽略了symbol
let id = Symbol("id");
let user = {
[id]: 123,
name:'1111'
};
let clone=Object.keys(user)
log( clone ); // [ 'name' ],忽略了symbol
const { log } = console
let id = Symbol("id");
let user = {
[id]: 123
};
let clone = Object.assign({}, user);
log( clone ); // { [Symbol(id)]: 123 },symbol依然存在
let id = Symbol.for("id");
let id1 = Symbol.for("id");
let user = {
[id]: 123,
[id1]: 234,
name:'1111'
};
log(user)// { name: '1111', [Symbol(id)]: 234 } 只有一个symbol