簡體   English   中英

遍歷嵌套數組

[英]Iterating over a nested array

我有一個包含3個項目的嵌套數組的數組,如下所示:

arr = [['first', 'second', 'third'],['one', 'two', 'three']];
$.each(arr, function (a, b, c) {
    console.log(a, b, c);
 });

當我使用上述代碼遍歷它們時,它console.logs:

0 Array [ "first", "second", "third" ] undefined  
1 Array [ "one", "two", "three" ] undefined

我如何將其記錄為:

'first', 'second', 'third'
'one', 'two', 'three'

像這樣使用forEach

arr.forEach(function(subarr, index) {        // loop over the array arr
    subarr.forEach(function(e, subindex) {   // loop over the sub-arrays of the array arr
        console.log(e);
    });
});

如果要使用jQuery.each ,請使用以下代碼:

$.each(arr, function(index, subarr) {        // loop over the array arr
    $.each(subarr, function(subindex, e) {   // loop over the sub-arrays of the array arr
       console.log(e);
    });
});

所需的輸出:

 var arr = [['first', 'second', 'third'],['one', 'two', 'three']]; arr.forEach(function(subarr, index) { var html = '<h1>' + subarr[0] + '</h1>'; html += '<p>' + subarr[1] + '</p>'; html += '<span>' + subarr[2] + '</span>'; console.log(html); //div.append(html); }); 

$.each()第一個參數是索引,第二個參數是值,因此您需要console.log b

 arr = [ ['first', 'second', 'third'], ['one', 'two', 'three'] ]; $.each(arr, function(a, b, c) { console.log(b); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

如果要從子數組中獲取每個元素,則需要嵌套循環。

 arr = [['first', 'second', 'third'],['one', 'two', 'three']]; $.each(arr, function(a, b) { $.each(b, function(i, e) { console.log(e); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

使用ES6,您也可以編寫此代碼。

 var arr = [['first', 'second', 'third'],['one', 'two', 'three']]; [].concat(...arr).forEach(e => console.log(e)) 

您可以使用數組解構為數組中的每個項目創建單獨的變量。

 var arr = [['first', 'second', 'third'],['one', 'two', 'three']]; arr.forEach(function(e) { var [a, b, c] = e; $('body').append('<h2>' + a + '</h2>' + '<p>' + b + '</p>' + '<span>' + c + '</span>' ) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

嘗試使用嵌套數組的join方法:

arr = [['first', 'second', 'third'],['one', 'two', 'three']];
$.each(arr, function (i, a) {
    console.log(a.join(", "));
 });

function(a,b,c)=> a表示索引,b表示項,而c並非沒有定義。

如果您只想迭代數組,

arr.forEach(function(item){
   console.log(item); // this will print inner arrays...
   // as in your case item is array, you can access their values using item[0], item [1]...
});

在javascript中,第一個參數是item,第二個是index,但是在jQuery中,第一個參數是index,第二個是item。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM