2016-08-04 152 views
-1

我有一個對象數組。循環遍歷對象數組中的項目

ABC.getAggregation("V")[0].getItems(); 

這產生的結果:

MY ARRAY OF OBJECTS

在控制檯中我能得到的結果我被指定這樣的項目的位置尋找:

ABC.getAggregation("V")[0].getItems()[0].getPosition() 
ABC.getAggregation("V")[0].getItems()[1].getPosition() 
ABC.getAggregation("V")[0].getItems()[2].getPosition() 

上述代碼的結果產生字符串值,例如「3.4554,43,0」。

如何循環瀏覽每個項目並獲取我的代碼中的位置。就像我在控制檯中輸入的上面的代碼一樣。那裏不會總是3個對象,這就是爲什麼我不能硬編碼上述3行。

+2

99%的有[MCVE(** M ** inimal,** C ** omplete,** V ** erifiable ** E ** xample)](http://stackoverflow.com/help/mcve)。 請發佈與您的問題相關的JavaScript/jQuery,CSS和HTML。使用任何或所有以下服務創建演示: [jsFiddle.net](https://jsfiddle.net/), [CodePen.io](https://codepen.io/), [Plunker。 (http://plnkr.co/), [JS Bin](https://jsbin.com/) 或片段(位於文本編輯器工具欄或CTRL + M上的第7個圖標)。 – zer00ne

+0

http:// stackoverflow。com/questions/38778974 /如何在函數內調用項目 – sarah

回答

1

嘗試使用該Array.prototype.forEach()函數。該函數將爲數組中的每個元素調用,並傳遞該元素作爲第一個參數。

ABC.getAggregation("V")[0].getItems().forEach(function (item) { 
    item.getPosition(); 
    //do something else 
}); 

更多關於 「.forEach()」

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

+0

謝謝! :) 有用! – sarah

+0

你能幫我解決這個問題嗎? http://stackoverflow.com/questions/38778974/how-to-call-items-from-an-array-inside-a-function – sarah

+0

你能幫我這個嗎? http://stackoverflow.com/questions/38778974/how-to-call-items-from-an-array-inside-a-function – sarah

-2

!!顯然,這是一個如何不要做一個很好的例子:P

您可以通過將它們分配項目到一個數組和循環是這樣的:

var items = ABC.getAggregation("V")[0].getItems(); 
var returnString = ""; 
for (var key in items) { 
    if (items .hasOwnProperty(key)) { 
    var element = items [key]; 
    returnString += element.getPosition() + ','; 
    } 
} 
returnString = returnString.substring(0, x.length-1); 
console.log(returnString); 
+1

爲什麼不只是爲了循環? –

+0

如何使用'forEach'或者仍然可以通過'for(var idx = 0,len = items.length; idx

+0

我的思路是,如果.getItems()在數組中返回一個未定義的值,我們不想迭代它並獲取未定義的錯誤。 –

1

您可以使用for循環迭代槽全部其中。

for(var i=0; i<ABC.getAggregation("V").getItems().length; i++) { 
    ABC.getAggregation("V")[0].getItems()[i].getPosition(); 
} 
+1

你在你的循環中缺少()。 「ABC.getAggregation(」V「)[0] .getItems()[i] .getPosition();' –

+0

感謝編輯@ChrisG –

+0

它說」getItems()不是函數「 – sarah

1

您可以像任何其他數組對待它:

var myArray = ABC.getAggregation("V")[0].getItems(); 
for(var i=0; i< myArray.length; i++){ 
    myArray[i].getPosition(); //Do something with the position. 
} 
+0

謝謝! :)它的作品 – sarah

+0

任何幫助這個? :) http://stackoverflow.com/questions/38778974/how-to-call-items-from-an-array-inside-a-function – sarah

1

您可以使用foreach循環槽所有這些迭代。

ABC.getAggregation("V").getItems().forEach (item, index) { 
    return ABC.getAggregation("V")[0].getItems()[index].getPosition(); 
} 
-1

一個非常簡單的方式,通過陣列中的每個對象進行迭代只是一個陣列上循環,你甚至都不需要聲明的迭代變量。

例如:

var anArray = ['one', 'two', 'three']; 

for(i in anArray){ 
    console.log('index #: ' + i); 
    console.log(anArray[i]); 
} 

將打印出所有的元素anArray:張貼要求的問題

index #: 0 

one 

index #: 1 

two 

index #: 2 

three