二维数组搜索从Python到Javascript

时间:2022-08-27 07:47:21

Whats is the equivalent of this code in Javascript?

什么是相当于Javascript中的这段代码?

array = ["James", "1", "3"]
array2 = ["Bob", "2", "5"]

mainArray = [array, array2]

Person = "James"

for element in mainArray:
    if (element[0] == Person):
        print Person + " " + "D=" + element[1] + " Z=" + element[2]

I have managed to create the arrays in Javascript but I am unsure how to code the for loop in a JS function.

我已经设法在Javascript中创建数组但我不确定如何在JS函数中编写for循环。

3 个解决方案

#1


1  

for(var i = 0; i < mainArray.length; i++){
    if(mainArray[i][0] == Person){
        console.log(mainArray[i][1] + " " + mainArray[i][2]);
    }
}

#2


0  

array = ["James", "1", "3"]
array2 = ["Bob", "2", "5"]
mainArray = array.concat(array2)
len = mainArray.length
for(var i=0;i<len;++i){
 if (mainArray[i] == "James"){
  console.log(mainArray[i]);
 }
}

#3


0  

Try this:

尝试这个:

var arr1 = ["James", "1", "3"],
    arr2 = ["Bob", "2", "5"]
    arrMain = [];
arrMain.push(arr1 , arr2);

for(x=0; x<arrMain.length; x+=1){
   (arrMain[x][0] === 'James') && 
   console.log(arrMain[x][0] + " " + "D=" + arrMain[x][1] + " Z=" + arrMain[x][2])
}    

#1


1  

for(var i = 0; i < mainArray.length; i++){
    if(mainArray[i][0] == Person){
        console.log(mainArray[i][1] + " " + mainArray[i][2]);
    }
}

#2


0  

array = ["James", "1", "3"]
array2 = ["Bob", "2", "5"]
mainArray = array.concat(array2)
len = mainArray.length
for(var i=0;i<len;++i){
 if (mainArray[i] == "James"){
  console.log(mainArray[i]);
 }
}

#3


0  

Try this:

尝试这个:

var arr1 = ["James", "1", "3"],
    arr2 = ["Bob", "2", "5"]
    arrMain = [];
arrMain.push(arr1 , arr2);

for(x=0; x<arrMain.length; x+=1){
   (arrMain[x][0] === 'James') && 
   console.log(arrMain[x][0] + " " + "D=" + arrMain[x][1] + " Z=" + arrMain[x][2])
}