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,
有時,您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 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?
對于常規屬性,我們可以輕松地使用點表示法,但是對于在點表示法之間使用空格的字符串屬性不起作用 。 那么,我們如何直接訪問這些屬性?
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 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,
方括號表示法用于鍵之間有空格的鍵,因為它以字符串作為參數。 讓我們再嘗試一些例子
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.
在這里,我們的教師對象有一個關鍵的項目顧問 ,其間有空格,我們使用方括號表示法訪問此屬性。
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
總結
以上是生活随笔為你收集整理的如何使用JavaScript访问对象的键中有空格的对象?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c#中将整数转化为字符串_在C#中将字符
- 下一篇: javascript对话框_JavaSc