Sometimes your JavaScript object may contain a key having spaces between them. As a key can also be a string and a string may contain spaces, it is very much possible that you encounter this problem. Consider the following object,
有时,您JavaScript对象可能包含一个键,它们之间有空格。 由于键也可以是字符串,并且字符串可能包含空格,因此很可能会遇到此问题。 考虑以下对象,
const character= {
name: 'Emily',
age: 30,
'Detective Rating': 422
}
console.log(character);
Output
输出量
{name: "Emily", age: 30, Detective Rating: 422}
Let's use the dot notation to access the properties of our object,
让我们使用点符号来访问对象的属性,
console.log(character.name);
console.log(character.Detective Rating);
console.log(character.'Detective Rating');
Output
输出量
Emily
Uncaught SyntaxError: missing ) after argument list
Uncaught SyntaxError: Unexpected string
For regular properties we can easily use the dot notation however for a string property having spaces in between the dot notation doesn't work. Then how do we directly access such properties?
对于常规属性,我们可以轻松地使用点表示法,但是对于在点表示法之间使用空格的字符串属性不起作用 。 那么,我们如何直接访问这些属性?
Remember, there is another way of accessing the object's properties, ie, using the square bracket notation.
请记住,还有另一种访问对象属性的方法,即使用方括号表示法。
console.log(character["name"]);
console.log(character["Detective Rating"]);
Output
输出量
Emily
422
The square bracket notation works for keys having spaces between them since it takes in a string as a parameter. Let's try some more examples,
方括号表示法用于键之间有空格的键,因为它以字符串作为参数。 让我们再尝试一些例子
const instructor={
ID: 'EC-203',
subject: 'Electronics',
'Project advisor': 'Digital signal processing documentation',
}
console.log(instructor["Project advisor"]);
Output
输出量
Digital signal processing documentation
Here our instructor object has a key Project advisor with space in between and we access this property using the square bracket notation.
在这里,我们的教师对象有一个关键的项目顾问 ,其间有空格,我们使用方括号表示法访问此属性。
const monsters={
'Monster names': ['Sesham','Goku','Samu']
}
console.log(monsters["Monster names"]);
Output
输出量
(3) ["Sesham", "Goku", "Samu"]
Our monsters have a property Monster names with space in between. This is an array and we have accessed this using the square bracket notation.
我们的怪物具有属性怪物名称 ,中间有空格。 这是一个数组,我们已经使用方括号符号访问了此数组。
翻译自: https://www.includehelp.com/code-snippets/how-to-access-an-object-having-spaces-in-the-objects-key-using-javascript.aspx