gpt4 book ai didi

javascript - 在javascript中比较二维数组和一维数组

转载 作者:行者123 更新时间:2023-12-03 06:42:54 25 4
gpt4 key购买 nike

var player1=["t1", "t9", "t7", "t8", "t2"];
var player2=["t5", "t3", "t4", "t6"];
var winmoves=[[t1,t2,t3],[t4,t5,t6],[t7,t8,t9],[t1,t4,t7],[t2,t5,t8],[t3,t6,t9],[t1,t5,t9],[t3,t5,t7]];

else if (moves>=3 && moves<=9) {
moves+=1;
if (turn==1) {
var i=0;
turn=2;
x.innerHTML="<img src='x.png'/>";
player1.push(x.id);
while(i<=moves){
if (winmoves[i] in player1) {
alert("player1 wins");
document.getElementById("player1").innerHTML=1;
}
i+=1;
}
}

我在javascript中有1d数组player1和2d数组winmoves,我想检查w[0]的所有值是否都存在于p中,等等w[1],w[2]等。if (player1 中的 winmoves[i]) 条件不起作用。我不知道我是否正在写这篇文章。帮帮我吧,我被困在这里了,我该怎么办。

即使我进行了这些更改,它也不起作用。

else if (moves>=3 && moves<9) {
moves+=1;
if (turn==1) {
var i=0;
turn=2;
x.innerHTML="<img src='x.png'/>";
player1.push(x.id);
while(i<=moves){
mapped1 = winmoves.map(a1 => a1.every(e1 => player1.includes(e1)));
if (mapped1[i]) {
alert("player1 wins");
document.getElementById("player1").innerHTML=1;
}
i+=1;
}
}
else if (turn==2) {
turn=1;
var i=0;
x.innerHTML="<img src='o.png'/>";
turn=1;
player2.push(x.id);
while(i<=moves)
{
mapped2 = winmoves.map(a => a.every(e => player2.includes(e)));
if (mapped2[i]) {
alert("player2 wins");
document.getElementById("player2").innerHTML=1;
}
i+=1;
}
}

}

最佳答案

我只需通过 Array.prototype.intersect() 的简单发明来完成此操作,其余的就是如此简单的单行代码。

Array.prototype.intersect = function(a) {
return this.filter(e => a.includes(e));
};

var player1 = ["t1","t2","t3","t5","t7"],
winmoves = [["t1","t2","t3"],["t4","t5","t6"],["t7","t8","t9"],["t1","t4","t7"],["t2","t5","t8"],["t3","t6","t9"],["t1","t5","t9"],["t3","t5","t7"]];
filtered = winmoves.filter(a => a.intersect(player1).length == a.length);
mapped = winmoves.map(a => a.intersect(player1).length == a.length);
console.log(filtered);
console.log(mapped);

好的,我们有一个通用的数组方法来查找两个数组的交集。 (在它调用的数组和作为参数提供的数组之间)它基本上是一个过滤器,检查第一个数组的每一项以查看它是否包含在第二个数组中。因此我们过滤掉两个数组中都存在的项目。

为了获得过滤后的数组,我们再次使用Array.prototype.filter()。这次我们的第一个数组是 winmoves,其中包含我们将检查与 player1 数组的每个交集的数组。如果交集长度等于 winmove 项目的长度,则意味着 winmove 项目的所有元素都存在于 player1 数组中。因此,我们将该数组项返回到filtered

根据您的情况,如果不使用 intersect 方法,您可以使用 Array.prototype.every() ,如下所示;

var player1 = ["t1","t2","t3","t5","t7"],
winmoves = [["t1","t2","t3"],["t4","t5","t6"],["t7","t8","t9"],["t1","t4","t7"],["t2","t5","t8"],["t3","t6","t9"],["t1","t5","t9"],["t3","t5","t7"]];
filtered = winmoves.filter(a => a.every(e => player1.includes(e)));
mapped = winmoves.map(a => a.every(e => player1.includes(e)));
console.log(filtered);
console.log(mapped);

关于javascript - 在javascript中比较二维数组和一维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37873437/

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