Concat first item of array to first itiem of second array JavaScript

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

how can I concat more rationally first item of array to first of second array and so on? Basically automate console.log here is the code:

$("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 

回答1:

I believe this is what you are looking for:

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


回答2:

If arrays have the same length, you could use map

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

Also you can use that result later, e.g.

console.log(result[0]); 


回答3:

Using es6 you can do the following:

(in your getJson callback):

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** } 

Your new whatIwant array will then contain objects for each set.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!