了解JavaScript中的对象

介绍 (Introduction)

An object in JavaScript is a data type that is composed of a collection of names or keys and values, represented in name:value pairs. The name:value pairs can consist of properties that may contain any data type — including strings, numbers, and Booleans — as well as methods, which are functions contained within an object.

JavaScript中的对象是一种数据类型 ,由名称的集合组成,以名称:值对表示 。 name:value对可以包含可以包含任何数据类型的属性 (包括字符串,数字和布尔值)以及方法 ,这些方法是对象中包含的函数。

Objects in JavaScript are standalone entities that can be likened to objects in real life. For example, a book might be an object which you would describe by the title, author, number of pages, and genre. Similarly, a car might be an object that you would describe by the color, make, model, and horsepower. JavaScript arrays are also a type of object.

JavaScript中的对象是独立的实体,可以与现实生活中的对象进行比对。 例如,一本书可能是一个对象,您可以通过标题,作者,页数和类型来描述。 同样,汽车可能是您要通过颜色,品牌,型号和马力来描述的对象。 JavaScript 数组也是一种对象。

Objects are an integral and foundational aspect of most JavaScript programs. For example, a user account object may contain such data as usernames, passwords, and e-mail addresses. Another common use case is a web shopping platform’s shopping cart that could consist of an array of many objects containing all the pertinent information for each item, such as name, price, and weight for shipping information. A to-do list is another common application that might consist of objects.

对象是大多数JavaScript程序不可或缺的基础部分。 例如,用户帐户对象可能包含诸如用户名,密码和电子邮件地址之类的数据。 另一个常见的用例是网络购物平台的购物车,它可以由许多对象组成,其中包含每个项目的所有相关信息,例如名称,价格和运输信息的重量。 待办事项列表是可能由对象组成的另一个常见应用程序。

In this tutorial, we will review how to create an object, what object properties and methods are, and how to access, add, delete, modify, and loop through object properties.

在本教程中,我们将回顾如何创建对象,什么是对象属性和方法,以及如何访问,添加,删除,修改和遍历对象属性。

创建一个对象 (Creating an Object)

An object is a JavaScript data type, just as a number or a string is also a data type. As a data type, an object can be contained in a variable.

对象是JavaScript数据类型 ,就像数字或字符串也是数据类型一样。 作为数据类型,对象可以包含在变量中。

There are two ways to construct an object in JavaScript:

使用JavaScript构造对象有两种方法:

  • The object literal, which uses curly brackets: {}

    对象文字 ,使用大括号: {}

  • The object constructor, which uses the new keyword

    对象构造函数 ,使用new关键字

We can make an empty object example using both methods for demonstration purposes.

出于演示目的,我们可以使用这两种方法创建一个空对象示例。

First, the object literal.

首先,对象文字。

// Initialize object literal with curly brackets
const objectLiteral = {}

The object literal initializes the object with curly brackets.

对象文字用括号将对象初始化。

In this next example, we’ll use the object constructor.

在下一个示例中,我们将使用对象构造函数。

// Initialize object constructor with new Object
const objectConstructor = new Object()

The same data was created using the object constructor method that is initialized with new Object().

使用使用new Object()初始化的对象构造函数方法创建了相同的数据。

Both of these approaches will create an empty object. Using object literals is the more common and preferred method, as it has less potential for inconsistencies and unexpected results.

这两种方法都会创建一个空对象。 使用对象字面量是更常见和首选的方法,因为它不太可能出现不一致和意外结果。

We can create an example object, contained in the variable gimli, to describe a character.

我们可以创建一个包含在变量gimli的示例对象来描述一个字符。

// Initialize gimli object
const gimli = {
name: 'Gimli',
race: 'dwarf',
weapon: 'axe',
greet: function () {
return `Hi, my name is ${this.name}!`
},
}

Our new object is gimli, which has three properties. Each property consists of a name:value pair, also known as key:value pair. weapon is one of the property names, which is linked to the property value "axe", a string. It has one method, with a method name of greet and the method value consisting of the contents of the function.

我们的新对象是gimli ,它具有三个属性。 每个属性都由一个name:value对组成,也称为key:value对。 weapon是属性名称之一,它链接到属性值"axe" (字符串)。 它有一个方法,方法名称为greet ,方法值由函数的内容组成。

Within greet, you may notice the this keyword. When using this inside of an object, it refers to the current object, in this case gimli.

greet ,您可能会注意到this关键字。 在对象内部使用this对象时,它指向当前对象,在本例中为gimli

Sending gimli to the console will print out the entire object.

gimli发送到控制台将打印出整个对象。

gimli{name: "Gimli", race: "dwarf", weapon: "axe", greet: ƒ}

This output may render differently depending on what console you are using, but you should notice that all of the values passed to the object are shown in the output.

根据使用的控制台,此输出可能会有所不同,但是您应注意,传递给该对象的所有值都显示在输出中。

Next, we will review a JavaScript object’s properties and methods.

接下来,我们将回顾JavaScript对象的属性和方法。

属性和方法 (Properties and Methods)

Objects can have properties and methods.

对象可以具有属性方法

A property is the association between a name (key) and value within an object, and it can contain any datatype. A property generally refers to the characteristic of an object.

属性是对象中名称(键)和值之间的关联,并且它可以包含任何数据类型。 属性通常是指对象的特征。

A method is a function that is the value of an object property, and therefore a task that an object can perform.

方法是作为对象属性值的函数,因此是对象可以执行的任务。

An easy way to remember the difference between object properties and methods is to think of a property as a noun, and a method as a verb. name, race and weapon are all nouns associated with an object, and are properties. fight() or talk() are verbs that might be used as a method function definition.

记住对象属性和方法之间差异的一种简单方法是将属性视为名词,将方法视为动词。 nameraceweapon都是与物体相关联的名词,并且是属性。 fight()talk()是可以用作方法功能定义的动词。

访问对象属性 (Accessing Object Properties)

There are two ways to access an object’s properties.

有两种访问对象属性的方法。

  • Dot notation: .

    点符号: .

  • Bracket notation: []

    括号符号: []

Let’s revisit our original example object, gimli.

让我们重新访问我们的原始示例对象gimli

const gimli = {
name: 'Gimli',
race: 'dwarf',
weapon: 'axe',
greet: function () {
return `Hi, my name is ${this.name}!`
},
}

If we want to retrieve the property value of weapon, we can do so with object dot notation by typing the variable name of the object, followed by a dot (.) and the property or method name.

如果要检索weapon的属性值,则可以使用对象点表示法来实现,方法是键入对象的变量名,后跟点( . )和属性或方法名。

// Retrieve the value of the weapon property
gimli.weapon"axe"

gimli.weapon outputs the property value, which is "axe". We can also retrieve the same data with object bracket notation. Similar to how you might index and access a string, the syntax for bracket notation is two square brackets ([]) encasing the property name.

gimli.weapon输出属性值,即"axe" 。 我们还可以使用对象括号符号检索相同的数据。 与您可能为索引和访问字符串的方式类似,括号符号的语法是两个包围属性名称的方括号( [] )。

// Retrieve the value of the weapon property
gimli['weapon']"axe"

Both dot notation and bracket notation are used regularly. Dot notation is faster and more readable, but has more limitations. Bracket notation allows access to property names stored in a variable, and must be used if an object’s property contains any sort of special character.

经常使用点符号和方括号符号。 点表示法更快,更易读,但有更多限制。 括号表示法允许访问存储在变量中的属性名称,如果对象的属性包含任何特殊字符,则必须使用括号表示法。

In order to retrieve an object method, you would call it much in the same way you would call a regular function, just attached to the object variable.

为了检索对象方法,您将以与调用常规函数相同的方式对其进行调用,只是将其附加到对象变量上。

gimli.greet()"Hi, my name is Gimli!"

In the example above, we see that the string value for the object method greet() is returned.

在上面的示例中,我们看到返回了对象方法greet()的字符串值。

We can now move on to modifying object properties through adding name:value pairs or modifying existing ones.

现在,我们可以通过添加name:value对或修改现有对象对来修改对象属性。

添加和修改对象属性 (Adding and Modifying Object Properties)

In order to add a new property to an object, you would assign a new value to a property with the assignment operator (=).

为了向对象添加新属性,您可以使用赋值运算符( = )将新值分配给属性。

For example, we can add a numerical data type to the gimli object as the new age property. Both the dot and bracket notation can be used to add a new object property.

例如,我们可以将数字数据类型添加到gimli对象中作为新的age属性。 点和括号符号都可用于添加新的对象属性。

// Add new age property to gimli
gimli.age = 139// Add new age property to gimli
gimli['age'] = 139

We can access that value just as above, with either the dot notation or the bracket notation.

我们可以像上面一样使用点符号或括号符号来访问该值。

gimli.age139

A method can also be added to the object by using the same process.

也可以使用相同的过程将方法添加到对象。

// Add new fight method to gimli
gimli.fight = function () {
return `Gimli attacks with an ${this.weapon}.`
}

Once we have created this new object method, we can call it as we did above.

一旦创建了这个新的对象方法,就可以像上面一样调用它。

gimli.fight()"Gimli attacks with an axe."

Using the same method, an object’s property can be modified by assigning a new value to an existing property.

使用相同的方法,可以通过将新值分配给现有属性来修改对象的属性。

// Update weapon from axe to battle axe
gimli.weapon = 'battle axe'

At this point, if we call the object, we will see all of our additions and modifications.

在这一点上,如果我们调用对象,我们将看到所有的添加和修改。

gimli{name: "Gimli", race: "dwarf", weapon: "battle axe", age: 139, greet: ƒ, fight: ƒ}

Through assignment operation, we can modify the properties and methods of a JavaScript object.

通过分配操作,我们可以修改JavaScript对象的属性和方法。

删除对象属性 (Removing Object Properties)

In order to remove a property from an object, you will utilize the delete keyword. delete is an operator that removes a property from an object.

为了从对象中删除属性,您将使用delete关键字。 delete是用于从对象中删除属性的运算符。

In the below example, we will remove the weapon property from gimli using delete.

在下面的示例中,我们将使用deletegimlidelete weapon属性。

// Remove weapon from gimli
delete gimli.weapontrue

The delete operation evaluates as true if the property was successfully removed, or if it was used on a property that doesn't exist.

如果已成功删除该属性,或者该属性用于不存在的属性,则delete操作的评估结果为true

We can test the output of gimli to see if it succeeded.

我们可以测试gimli的输出,看看是否成功。

gimli{name: "Gimli", race: "dwarf", age: 139, greet: ƒ, fight: ƒ}

In the above output, the weapon name and its associated value are no longer available, showing that we have successfully deleted the property.

在上面的输出中, weapon名称及其关联值不再可用,表明我们已成功删除该属性。

In the next section, we’ll go over ways to iterate through objects in JavaScript.

在下一节中,我们将介绍遍历JavaScript对象的方法。

遍历对象属性 (Looping Through Object Properties)

JavaScript has a built-in type of for loop that is specifically meant for iterating over the properties of an object. This is known as the for...in loop.

JavaScript具有内置的for循环类型,专门用于遍历对象的属性。 这称为for...in循环。

Here is a simplified version of our main object example, gimli.

这是我们的主要对象示例gimli的简化版本。

const gimli = {
name: 'Gimli',
race: 'dwarf',
weapon: 'battle axe',
}

We can use for...in to traverse through all the properties of gimli and print them to the console. Using bracket notation, we can retrieve the property value as a variable, in this case key.

我们可以使用for...in遍历gimli所有属性并将它们打印到控制台。 使用括号符号,我们可以将属性值检索为变量,在本例中为key

// Iterate through properties of gimli
for (let key in gimli) {
console.log(gimli[key])
}Gimli
dwarf
battle axe

We can also retrieve the property name itself using just the first variable in the for...in loop. We have used a string method to convert the key values to upper case.

我们也可以仅使用for...in循环中的第一个变量来检索属性名称本身。 我们已经使用字符串方法将键值转换为大写

// Get keys and values of gimli properties
for (let key in gimli) {
console.log(key.toUpperCase() + ':', gimli[key])
}NAME: Gimli
RACE: dwarf
WEAPON: battle axe

The for...in loop is not to be confused with the for...of loop, which is used exclusively on the Array object type. You can learn more about iterating through arrays in the "Understanding Arrays in JavaScript" tutorial.

for...in循环不要与for...of循环混淆,后者仅在Array对象类型上使用。 您可以在“ 了解JavaScript中的数组 ”教程中了解有关遍历数组的更多信息。

Another useful enumeration method is the Object.keys() method, which will return an array of the object's keys.

另一个有用的枚举方法是Object.keys()方法,该方法将返回对象键的数组。

// Initialize method on gimli object to return property keys
Object.keys(gimli)["name", "race", "weapon"]

This method allows us to work with the keys or names of an object as an array, so you can leverage all of the methods available to JavaScript arrays.

此方法使我们可以将对象的键或名称作为数组使用,因此您可以利用JavaScript数组可用的所有方法。

结论 (Conclusion)

Objects are an extremely useful and versatile feature of the JavaScript programming language. They are some of the main building blocks of writing code in JavaScript, and are a practical way to organize related data and functionality. To-do lists, shopping carts, user accounts, and locations on a webmap are all a few of the many examples of real-world JavaScript objects that you might encounter.

对象是JavaScript编程语言的一项极其有用且用途广泛的功能。 它们是用JavaScript编写代码的一些主要构件,并且是组织相关数据和功能的实用方法。 待办事项列表,购物车,用户帐户和网络地图上的位置都是您可能会遇到的现实世界JavaScript对象的众多示例中的一些。

普通英语JavaScript (JavaScript In Plain English)

Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

喜欢这篇文章吗? 如果是这样,请订阅我们的YouTube频道解码,以获得更多类似的内容

翻译自: https://medium.com/javascript-in-plain-english/understanding-objects-in-javascript-c81c4012be45

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值