Create objects using object literals
//用对象字面量声明对象font,包含属性size,值为16;方法changeFontsize,形参为n,方法(函数)体如下,方法(函数)中访问size
const font ={
size:16,
changeFontsize(n){
if (this.size+n < 14 || this.size+n > 22){
return;
}
size+= n;
document.body.style.fontSize = size + 'px';}}
Access the object's key:
(1) Object.Key name
Assigning a value to a key that does not exist in the object will add the key/value pair
let obj={'a':5,b:1,doit:function(){}};
obj.a=6;
obj.c=8;
let x=obj.a;
let y=obj.doit();
obj.d; obj.f();//调用不存在的方法会出错
(2) object [key name]
Key names can be primitive data types or expressions (variables)
[ ] can be accessed. Keys that cannot be accessed will not go wrong with [ ]
let obj={width:60,'font-size':9};
obj['width']=80;
obj['font-size']=16;
let key='id';
obj[key]='top';
Iterate over the keys and values of an object
for(variable in object)
let person={name:'小明',
age:'20'}
for (let key in person){
console.log(key+":"+person[key]);}
for (variable of iterable objects)
same as above