javascript
如何使用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,
有時(shí),您JavaScript對(duì)象可能包含一個(gè)鍵,它們之間有空格。 由于鍵也可以是字符串,并且字符串可能包含空格,因此很可能會(huì)遇到此問(wèn)題。 考慮以下對(duì)象,
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,
讓我們使用點(diǎn)符號(hào)來(lái)訪問(wèn)對(duì)象的屬性,
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 stringFor 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?
對(duì)于常規(guī)屬性,我們可以輕松地使用點(diǎn)表示法,但是對(duì)于在點(diǎn)表示法之間使用空格的字符串屬性不起作用 。 那么,我們?nèi)绾沃苯釉L問(wèn)這些屬性?
Remember, there is another way of accessing the object's properties, ie, using the square bracket notation.
請(qǐng)記住,還有另一種訪問(wèn)對(duì)象屬性的方法,即使用方括號(hào)表示法。
console.log(character["name"]); console.log(character["Detective Rating"]);Output
輸出量
Emily 422The 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,
方括號(hào)表示法用于鍵之間有空格的鍵,因?yàn)樗宰址鳛閰?shù)。 讓我們?cè)賴L試一些例子
const instructor={ID: 'EC-203',subject: 'Electronics','Project advisor': 'Digital signal processing documentation', }console.log(instructor["Project advisor"]);Output
輸出量
Digital signal processing documentationHere our instructor object has a key Project advisor with space in between and we access this property using the square bracket notation.
在這里,我們的教師對(duì)象有一個(gè)關(guān)鍵的項(xiàng)目顧問(wèn) ,其間有空格,我們使用方括號(hào)表示法訪問(wèn)此屬性。
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.
我們的怪物具有屬性怪物名稱 ,中間有空格。 這是一個(gè)數(shù)組,我們已經(jīng)使用方括號(hào)符號(hào)訪問(wèn)了此數(shù)組。
翻譯自: https://www.includehelp.com/code-snippets/how-to-access-an-object-having-spaces-in-the-objects-key-using-javascript.aspx
總結(jié)
以上是生活随笔為你收集整理的如何使用JavaScript访问对象的键中有空格的对象?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c#中将整数转化为字符串_在C#中将字符
- 下一篇: ruby 类方法与实例方法_Ruby S