原文地址:https://dev.to/bhagatparwinder/what-are-objects-in-javascript-19oi
对象是 JavaScript 中基础的构成模块,JavaScript 中一切皆可表示为对象。
对象是键值对的形式,key 是对 value 的引用。下面看一下例子:
const person = {
firstName: "Parwinder",
lastName: "Bhagat",
'my name':'Parwinder Bhagat',
age: 33,
nicknames: ["Ricky", "P"],
vehicles: {
car: "BMW X5",
motorcycle: "Honda Rebel 500"
}
}
上面我声明了一个 person 的对象,它是独立数据的集合。对象是用一个 **{}**表示的。在中括号内,左边是 key (不需要使用引号)冒号右边是 value 。
注意:时刻记住对象中 key 的顺序没关系,无法保证对象中的 key 顺序。
为了获取对象里的值,你需要引用 key 来寻找。例如:
console.log(person.firstName); // Parwinder
console.log(person.lastName); // Bhagat
console.log(person.age); // 33
console.log(person.nicknames); // ["Ricky", "P"]
console.log(person.vehicles.car); // BMW X5
You can also refer
你同样可以使用中括号形式来获取值:
console.log(person["age"]); // 33
注意:点语法是首选存取方式,除非访问属性时必须使用变量:key 包含导致语法错误的字符或关键字、保留字时。
console.log(person["my name"]); //
就像给变量赋值一样,你可以给对象中的 key 赋值任何类型的值。在我上面的例子中,我为 key 赋值了 字符串、数字、数组和对象类型。
person.firstName = "Julius";
person.lastName = "Caesar";
person.age = 48;
person.vehicles = null;
你可以使用:
使用 delete 操作符:
delete(person.age);
console.log(person.name); // Julius
console.log(person.age); // undefined
当然可以
person.greeting = function(greeting = "Hola") {
return `${greeting} ${this.firstName}`;
};
person.greeting("Salute"); // Salute Julius
person.greeting(); // Hola Julius