簡體   English   中英

將數組的第一項連接到第二個數組的JavaScript的第一個項目

[英]Concat first item of array to first itiem of second array JavaScript

如何更合理地將數組的第一項連接到第二個數組的第一個,依此類推? 基本上自動化console.log,這里是代碼:

$("button#search").on("click", function(){
var inputVal = $("input#text").val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + inputVal +"&limit=5&namespace=0&format=json&callback=?", function(json) {
    var itemName = $.each(json[1], function(i, val){    
    })
    var itemDescription = $.each(json[2], function(i, val){ 
    })
    var itemLink = $.each(json[3], function(i, val){
    })
    console.log(itemName[0] + " " + itemDescription[0] + " " + itemLink[0]);
    console.log(itemName[1] + " " + itemDescription[1] + " " + itemLink[1]);
    console.log(itemName[2] + " " + itemDescription[2] + " " + itemLink[2]);
    console.log(itemName[3] + " " + itemDescription[3] + " " + itemLink[3]);
    console.log(itemName[4] + " " + itemDescription[4] + " " + itemLink[4]);
    })//EOF getJSON
});//EOF button click

我相信這是您要尋找的:

for (var i = 0; i < itemName.length; i++) {
  console.log(itemName[i] + " " + itemDescription[i] + " " + itemLink[i]); 
}

如果數組的長度相同,則可以使用map

var result = $.map(json[1], function(i, val){
    var row = val + " " + json[2][i] + " " + json[3][i];
    console.log(row);
    return row;
}

您也可以稍后使用該result ,例如

console.log(result[0]);

使用es6,您可以執行以下操作:

(在您的getJson回調中):

function (json) {
    const [value, optionsJ, descriptionsJ, linksJ] = json;
    let whatIwant = [];

    // choose one to loop through since you know they will all be the same length:
    optionsJ.forEach(function (option, index) {
        whatIwant.push({option: option, description: descriptionJ[index], link: linksJ[index]});
    });

    // use whatIwant here**
}

新的whatIwant數組將包含每個集合的對象。

暫無
暫無

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

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