gpt4 book ai didi

javascript - 数组内边界的条件

转载 作者:行者123 更新时间:2023-11-28 04:18:50 25 4
gpt4 key购买 nike

我有一个矩阵,我有一个函数可以使用以下代码随机选择数组的一个元素:

npcSelectShip() {
let selectCol = () => {
let colIndex = Math.floor(Math.random() * this.npcSelectionField.length);
let selectCell = () => {
let cellIndex = Math.floor(Math.random() * this.npcSelectionField[colIndex].length);
if (this.npcSelectionField[colIndex][cellIndex].isEmpty === false) {
selectCell();
} else {
this.npcSelectionField[colIndex][cellIndex].isEmpty = false;
this.pickDirection(this.npcSelectionField, colIndex, cellIndex);
}

}

selectCell();
}

selectCol();
}

在此之后,我有另一个函数来搜索随机选取元素的邻居(顶部、右侧、底部和左侧),随机选取一个邻居并更改属性:

    pickDirection(field, col, cell) {
let neighbors = [];
neighbors.push(
field[col - 1][cell],
field[col + 1][cell],
field[col][cell - 1],
field[col][cell + 1]
);
let randDir = () => {
let randIndex = neighbors[Math.floor(Math.random() * neighbors.length)];
if (randIndex.isEmpty === false) {
randDir();
} else {
randIndex.isEmpty = false;
}
}

randDir();
}

我面临的问题是,当随机选取的元素的索引为 0 或等于数组长度时,因为如果它选取索引为 1 或索引+1 处的邻居,则它基本上是“越界”我收到这些错误:

TypeError: Cannot read property 'isEmpty' of undefined
TypeError: Cannot read property '9' of undefined

有没有一种方法可以解决这个问题,而不必编写大量的 ifs 和 elses ?

感谢您的帮助。

最佳答案

您可以使用Array.concat和一个默认模式,它返回一个空数组。

concat结合使用,空数组充当中性值。

var neighbors = [].concat(
(field[col - 1] || [])[cell] || [],
(field[col + 1] || [])[cell] || [],
(field[col] || [])[cell - 1] || [],
(field[col] || [])[cell + 1] || []
);

或者使用包装器来访问

function getCell(array, col, cell) {
return (array[col] || [])[cell] || [];
}

使用

var neighbors = [].concat(
getCell(field, col - 1, cell),
getCell(field, col + 1, cell),
getCell(field, col, cell - 1),
getCell(field, col, cell + 1)
);

How it works

(field[col - 1] || [])[cell] || []

It tries to get the value of

 field[col - 1]

and if the value is undefined,

 field[col - 1] || []

it returns an empty array, with the locical logical OR || operator. What we get is either the array of field[col - 1] or an empty array [].

For the next index, we use the same pattern and check if

(field[col - 1] || [])[cell]

exists and if not then we take another empty array as result

(field[col - 1] || [])[cell] || []

Now we have either a truthy value, like an object or an empty array.

This is necessary, because empty arrays are not added to an array with Array.concat.

关于javascript - 数组内边界的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45615851/

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