如何使用JavaScript访问对象的键中有空格的对象?

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值