2013-12-08 88 views
-3

值我有對象的一個​​這樣的數組:使用的console.log以顯示對象

Object {index: "4", value: -1} 
Object {index: "0", value: 0} 
Object {index: "6", value: 0} 
Object {index: "8", value: 0} 
Object {index: "1", value: 1} 
Object {index: "3", value: 1} 
Object {index: "5", value: 1} 
Object {index: "7", value: 1} 

非常第一個爲0的指標,我可以像console.log[array[0]訪問它,這將現在給我Object {index: "4", value: -1}如果不使用對象數組的索引,我想通過對象內部的valueindex來訪問它。我嘗試了幾個不同的命令。

console.log(array["index: " + 8] 
console.log(array["index:" == 8] 

都未做任何東西,除了拋出未定義或錯誤的以上兩個例子,我想他們打印出來Object {index: "8", value: 0}我希望這是有道理的

+2

'console.log [array [0]'是各種破碎的語法。 – meagar

+1

恐怕JavaScript不能以這種方式工作。你需要搜索和/或循環數組,以便做到這一點。 – Boaz

+0

你需要編寫一個小函數來循環數組以找到一個元素,或者使用像jQuery這樣的外部庫。 jQuery的函數是'.inArray'。 SO – foibs

回答

1

JavaScript的property accessors不能Object秒鐘內看正在舉行的Array對他們適用的條件。

最接近的選項,這可能是.filter()

var filtered = array.filter(function (item) { 
    return item.index === "8"; 
}); 

console.log(filtered[0]); // Object {index: "8", value: 0} 

你也可以使用一個for loopif test找到它。

0

沒有什麼可以做8這裏。這完全不是你如何使用JavaScript中的對象,因爲即使是最基本的教程也會顯示給你。

鑑於obj = {index: "4", value: -1},您可以使用obj.indexobj.value訪問這兩個值。你不能發明一些怪異的東西,並期待理智的結果。

obj = {index: "4", value: -1} 

console.log(obj.index) // 4 
console.log(obj.value) // -1 

如果你想找到具有8個指標,即涉及順序掃描陣列與一個循環,不寫一些僞查詢語言的對象。

1

fiddle Demo

function find_index(x) { 
    var y = ''; 
    for (var i = 0; i < arr.length; i++) { 
     if (arr[i].index == x) { 
      y = arr[i]; 
      break; 
     } 
    } 
    return y; 
} 
console.log(find_index(8)); //Object {index: "8", value: 0} 
相關問題