[英]Array push method behaving strangely javascript
我有一个 function 将数组作为参数
[["52", ["41", "43", "61", "63"]], ["54", ["43", "45", "63", "65"]]]
“52”是我的硬币, ["41", "43", "61", "63"]
是硬币“52”的可能移动位置。 这同样适用于 "54" 和["43", "45", "63", "65"]
。
在我的情况下cell.innerHTML == ''
用于位置“41”、“43”、“45”
function 行为正确,直到freeLocations.push(freeLocation);
它的输出在哪里
["52", "41"], ["52", "43"], ["54", "43"] and ["54", "45"].
但是,allFreePostions.push(freeLocations) 仅输出 3 个 arrays:["52", "41"], ["52", "43"] 和 ["54", "45"]。 ["54", "43"] 丢失。
奇怪的是,如果我只是为了调试而编辑freeLocations.push(freeLocation, j)
,丢失的数组会显示在allFreePostions.push(freeLocations)
中。
我在这里错过了什么吗?
function checkFreeLocations(coins){ let allFreePostions = []; let dangerPosition = []; for (let i = 0; i < coins.length; i++){ coin = coins[i][0]; positions = coins[i][1]; for (let j = 0; j < positions.length; j++){ let freeLocations = []; let cell = document.getElementById(positions[j]); if (cell.innerHTML == ''){ freeLocation = positions[j]; freeLocations.push(coin); freeLocations.push(freeLocation); allFreePostions.push(freeLocations); } } } } checkFreeLocations([["52", ["41", "43", "61", "63"]], ["54", ["43", "45", "63", "65"]]])
看起来您的 HTML 中有非唯一 ID,这给您带来了麻烦。
我相信 ["54", "43"] 未显示的原因是因为您查看元素是否为空:
let cell = document.getElementById(positions[j]); if (cell.innerHTML == ''){ freeLocation = positions[j]; freeLocations.push(coin); freeLocations.push(freeLocation); allFreePostions.push(freeLocations); }
这种情况可能是您之前已经用 ['52', '43'] 填充了该元素。 但请添加您的 HTML 以便于掌握。
我不知道这是否有帮助,但这就是我更改硬币内所有数据的方式。
let coins = [ ["52", ["41", "43", "61", "63"]], ["54", ["43", "45", "63", "65"]] ]; console.log(coins); function checkFreeLocations(coins){ let allFreePostions = []; for (let i = 0; i < coins.length; i++){ let freeLocations = []; freeLocations.push(i); let freeLocation = []; for (let j = 0; j < coins[i][1].length; j++){ let change = 'X'; freeLocation.push(change); } freeLocations.push(freeLocation); allFreePostions.push(freeLocations); } return allFreePostions; } console.log(checkFreeLocations(coins));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.