[英]Iterating Array of Objects in javascript
我有一個數組,其中包含一個帶有鍵的對象,值我們如何迭代每個對象的caste
和id
。
[
Object {
caste = "Banda",
id = 4
},
Object {
caste = "Bestha",
id = 6
}
]
使用jQuery.each()
:
var array = [ {caste: "Banda", id: 4}, {caste: "Bestha", id: 6} ]; $.each(array, function( key, value ) { console.log('caste: ' + value.caste + ' | id: ' +value.id); } );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
示例代碼:
var list = [ { caste:"Banda",id:4}, { caste:"Bestha",id:6}, ]; for (var i=0; i<list.length; i++) { console.log(list[i].caste); }
它只是一個數組,所以,一如既往地迭代它。
在純JavaScript中,您可以這樣做:
var array = [{caste: "Banda", id: 4}, {caste: "Bestha", id:6}];
array.forEach(function(element, index) {
console.log(element.id+" "+element.caste);
});
使用第三個參數調用回調函數,即遍歷的數組。 了解更多 !
因此,您不需要加載jQuery庫。
問候。
var array = [{caste: "Banda", id: 4}, {caste: "Bestha", id:6}];
var length = array.length;
for (var i = 0; i < length; i++) {
var obj = array[i];
var id = obj.id;
var caste = obj.caste;
}
箭頭功能現代是現代的
使用帶箭頭功能的jquery $ .each
var array = [
{caste: "Banda", id: 4},
{caste: "Bestha", id: 6}
];
$.each(array, ( key, value ) => {
console.log('caste: ' + value.caste + ' | id: ' +value.id);
});
使用帶箭頭功能的forEach
array.forEach((item, index) => {
console.log('caste: ' + item.caste + ' | id: ' +item.id);
});
使用帶箭頭功能的地圖。 這里map返回一個新數組
array.map((item, index) => {
console.log('caste: ' + item.caste + ' | id: ' +item.id);
});
forEach循環接受迭代器函數,並且可選地,在調用迭代器函數時使用一個值作為“this”。
var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }
];
donuts.forEach(function(theDonut, index) {
console.log(theDonut.type + " donuts cost $"+ theDonut.cost+ " each");
});
隨后它也可以分解為此
var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }
];
function ShowResults(donuts) {
console.log(donuts.type + " donuts cost $"+ donuts.cost+ " each");
}
donuts.forEach(ShowResults);
你可以使用jquery迭代jQuery希望你填充回調函數的所有對象,jquery將回調它。 第一個輸入參數將被賦予鍵,第二個輸入參數將被賦予值:
$.each(dataList, function(index, object) {
$.each(object,function(attribute, value){
alert(attribute+': '+value);
});
});
使用jQuery.each :
$.each([your array of objects], function(index, value) {
// Do what you need, for example...
alert(index + ': ' + value);
});
要迭代jQuery中填充了東西的數組,請使用$ .each來迭代一個Object,因為它的屬性使用for..in
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.