Two reference methods of objects in JavaScript ".", "[] "

How to reference properties in javascript objects (how to use obj.[key])

In javascript, generally we use "." to refer to the value in the constant in the object .

// 例子
var obj = {
    
    
	name:"此行月相随"
};
//使用 .
console.log(obj.name)  //此行月相随 
//此处如果使用 [] 需要在里面添加''
console.log(obj['name'])  //此行月相随 

But if the properties in the object are undefined, then you need to use[ ]to reference the value in it.

// 例子
var obj = {
    
    
	name:"此行月相随"
	age:"13"
	sex:"男"
};
for(let key in obj){
    
    
	console.log(obj[key])    //正确
	console.log(obj.key)    //错误  undefined
}

Guess you like

Origin blog.csdn.net/weixin_50407990/article/details/128189793