我正在使用JavaScript比较单个数组和多维数组。 在这里,我想比较那两个数组,并显示匹配的值。
arr[1,2,3]
值。这是我的代码::我采用了一个数组,另一个作为多维数组
var arr = [1,2,3];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
for(var j=0; j<md2.length ; j++){
if(arr == md2[j]){
console.log(arr + " ... " + md2[j]);
}
}
所需的O / P:-[1,2,3]
应该匹配并显示在控制台中
答案 0 :(得分:0)
您可以使用.find()
和.every()
方法在多维数组中查找数组:
var arr1 = [1,2,3];
var arr2 = [1,2,5];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
var searchAndPrint = (a1, a2) => {
let arr = a1.find(a => a.every((v, i) => v === a2[i]));
if(arr)
console.log(arr);
else
console.log("No Results");
};
searchAndPrint(md2, arr1);
searchAndPrint(md2, arr2);
答案 1 :(得分:0)
您无法在js中比较arrays
。如果您想比较简单数组,可以将它们转换为string
进行比较。此方法不适用于包含objects
的数组。
var arr = [1,2,3];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
for(var j=0; j<md2.length ; j++){
if(arr.toString() === md2[j].toString()){
console.log(arr + " ... " + md2[j]);
}
}
答案 2 :(得分:0)
您可以使用JSON.stringify
比较数组。
var arr = [1,2,3];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
for(var j=0; j<md2.length ; j++){
if(JSON.stringify(arr) === JSON.stringify(md2[j])){
console.log(arr + " ... " + md2[j]);
}
}
答案 3 :(得分:0)
要检查,您需要直接检查长度和项目,因为没有相同的对象引用。
import os
import time
import random
# Define the board
board = [" "," "," "," "," "," "," "," "," "," "]
#Define the print_board function
def print_board():
print (" | | ")
print (" "+board[1]+" | "+board[2]+" | "+board[3]+" ")
print (" | | ")
print ("---|---|---")
print (" | | ")
print (" "+board[4]+" | "+board[5]+" | "+board[6]+" ")
print (" | | ")
print ("---|---|---")
print (" | | ")
print (" "+board[7]+" | "+board[8]+" | "+board[9]+" ")
print (" | | ")
os.system("clear")
print(a)
print_board()
n1=str(input("Enter Player 1 name")
n2=str(input("Enter Player 2 name")
b=str(input("Choose your symbol")
if b== "X" or "x":
choice = input("Please select the place for your symbol X")
board(choice) = "X"