我想根據數組中的第一個值訪問對象屬性。基於數組值訪問對象屬性
var LANGS = {
"C#": [10, "text/x-csharp", "code"],
"C/C++": [7, "text/x-c++src", "code"]
};
所以我希望能夠訪問其陣列中的10
"C#"
,我會怎麼做這個?
我想根據數組中的第一個值訪問對象屬性。基於數組值訪問對象屬性
var LANGS = {
"C#": [10, "text/x-csharp", "code"],
"C/C++": [7, "text/x-c++src", "code"]
};
所以我希望能夠訪問其陣列中的10
"C#"
,我會怎麼做這個?
您可以使用for-in
遍歷對象的屬性名稱,然後會按順序使用名稱的屬性的值,以檢查它的第一個元素:
var LANGS = {
"C#": [10, "text/x-csharp", "code"],
"C/C++": [7, "text/x-c++src", "code"]
};
function getEl(number) {
for(var el in LANGS) {
if(LANGS[el][0] == number) {
return el;
}
}
}
alert(getEl(10));
爲什麼downvote? –
爲什麼downvote?這就假定找到該屬性該怎麼做,但是它確實解答了問題:顯示如何根據該值找到屬性。 –
這裏的值是數組,不確定indexOf是否可以作爲值在數組上工作... –
var LANGS = {
"C#": ["text/x-csharp", "code",10],
"C/C++": [7, "text/x-c++src", "code"]
};
function getEl(number) {
for(var el in LANGS) {
debugger
var array = [];
array = LANGS[el];
if(array.indexOf(number) > -1) {
return el;
}
}
}
alert(getEl(10));
這甚至意味着「訪問」C#「由其數組中的10 * *」? – Amit
@如果提供了'10',就可以獲得鑰匙'C#' – Tushar
@Tushar如果你是對的,我會說不這樣做。用適當的鍵設置一個新的「詞典」。 – Amit