我正在尝试在 ReactJS 中创建这个内存游戏,并且我创建了一个数组,在其中添加了 4 个随机数。现在,每次我按“玩游戏”时,我都需要用 4 个随机数 0 到 3 填充数组,但我不断收到数组中不知从何而来的随机逗号。我对 React 还很陌生,所以非常感谢您的帮助。
我尝试了不同的方法来填充数组,但逗号仍然出现。 P.S: keepArray 在 for 循环之前初始化。
for (let i = 0; i < 4; i++) {
let rand = Math.floor(Math.random() * 4)
keepArray = [...keepArray + rand]
console.log(keepArray)
}
最佳答案
解决方案:
替换:
keepArray = [...keepArray + rand]
与:
keepArray = [...keepArray, 兰特]
说明:
扩展运算符(...
)实际上是“扩展”您的数组,这就是您需要逗号的原因。下面的例子可能有助于形象化:
// Let's start with a simple array:
var myArray = [1, 2, 3];
// Now, we add another element to it using spread:
var updatedArray = [...myArray, 4];
// Here, ...myArray is translated to [1, 2, 3]
// That means that the above could be read as:
var updatedArray = [1, 2, 3, 4];
引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
<小时/>有关“+”行为的额外说明,请参阅 Pavan Bahuguni 答案。
关于javascript - ReactJS 数组中出现随机逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56436741/