gpt4 book ai didi

javascript - 在 Javascript 中匹配两个多维数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:30:14 25 4
gpt4 key购买 nike

我有两个多维数组,我想创建第三个多维数组:

var reports = [
[48.98,153.48],
[12.3,-61.64]
];

var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];

我想创建一个新的多维数组

var nuovarray= [];  


for (i=0; i<= reports.length; i++) {

var attivi= reports[i];
var attlat= attivi[0];
var attlng= attivi[1];

for (s=0; s<=vulc.length; s++){
var vulca= vulc[s];
var vulcanam= vulca[0];
var vulcalat= vulca[1];
var vulcalng= vulca[2];

if ((vulcalat==attlat) && (vulcalng==attlng){
var stato= "A";
nuovarray.push([vulcanam,vulcalat,vulcalng,stato]);
}
else{
var stato= "N";
nuovaarray.push([vulcanam,vulcalat,vulcalng,stato]);
}

}

}

我想拥有

var nuovarray= [
["ciccio",48.98,153.48,"N"],
["cicci",12.3,-61.64,"N"],
["intruso",59.9,99.9,"A"]
];

但是我不知道这段代码好不好:/

最佳答案

正如我在评论中所说,在 for 循环中,使用 < not <= (array of length N has indexes 0 ... N-1) ... 并将外循环与内循环交换,并且仅如果内循环没有用值“A”推送,则在外循环结束前用值“N”推送

var reports = [
[48.98,153.48],
[12.3,-61.64]
];

var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];

var nuovarray= [];

for(var s = 0; s < vulc.length; s++) {
var vulca = vulc[s];
var stato= "A"; // default, no match
var vulcanam= vulca[0];
var vulcalat= vulca[1];
var vulcalng= vulca[2];

for(var i = 0; i < reports.length; i++) {
var attivi = reports[i];
var attlat= attivi[0];
var attlng= attivi[1];

if ((vulcalat==attlat) && (vulcalng==attlng)) {
stato = "N";
break; // we've found a match, so set stato = N and stop looping
}
}
nuovarray.push([vulcanam,vulcalat,vulcalng,stato]);
}


document.getElementById('result').innerHTML = (nuovarray).toSource();
<div id='result'></div>

关于javascript - 在 Javascript 中匹配两个多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31770774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com