创建对象
// 对象字面值; key需要为字符串
let folder1 = {
'size' : 2000,
'name' : 'folder1',
'subFile' : ['index.js'],
'other object' : null
};
console.log(typeof folder1, folder1);
输出如下
object {
size: 2000,
name: 'folder1',
subFile: [ 'index.js' ],
'other object': null
}
// 合法标识符可以省略冒号
let folder2 = {
size : 2000,
name : 'folder2',
subFiles : ['index.js'],
'other object' : folder1
};
console.log(folder2.name, folder2.subFiles);
console.log(folder2['name'], folder2['subFiles']);
let a = 'subFiles';
console.log(folder2['na'+'me'], folder2[a]);
//三个输出等价 folder2 [ 'index.js' ]
//链式调用
console.log(folder2['other object'].subFile[0]);
若访问一个未定义对象,返回undefined
访问修改
可以随意修改
folder2.size = folder2.size + 100;
对象属性可变且可以增加新属性
folder2.NEWOBJECT = 'no';
folder2["new object"] = "yes"
console.log(folder2);
输出
{
size: 2100,
name: 'folder2',
subFiles: [ 'index.js' ],
'other object': {
size: 2000,
name: 'folder2',
subFile: [ 'index.js' ],
'other object': null
},
NEWOBJECT: 'no',
'new object': 'yes'
}
动态增删
有时候我们希望 属性的名字是计算出来的。而不是固定的
let str = 'vairable';
const obj = {