You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:无法在JavaScript二维数组中存储字符的问题

问题排查与解决:JavaScript二维数组字符赋值后显示异常

你给二维数组赋值字符的操作是成功的,问题出在console.log的输出代码里的一元加号运算符上。

问题原因

看你的console.log语句,比如" ", + gameBoard[0][0]这里的+是一元加号,作用是把后面的变量强制转换成数字类型。当你把gameBoard[1][1]设为字符串"a"后,+ gameBoard[1][1]会尝试将字符串"a"转换为数字,结果得到NaN(非数字值),所以输出时看起来像是没存储成功,但实际上数组里的"a"已经正常存进去了。

解决方法

去掉所有console.log里的一元加号,修改后的代码如下:

let gameBoard = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(" ", gameBoard[0][0] + " |", gameBoard[0][1] + " | " + gameBoard[0][2]);
console.log(" ", gameBoard[1][0] + " |", gameBoard[1][1] + " | " + gameBoard[1][2]);
console.log(" ", gameBoard[2][0] + " |", gameBoard[2][1] + " | " + gameBoard[2][2]);

gameBoard[1][1] = "a";

console.log(" ", gameBoard[0][0] + " |", gameBoard[0][1] + " | " + gameBoard[0][2]);
console.log(" ", gameBoard[1][0] + " |", gameBoard[1][1] + " | " + gameBoard[1][2]);
console.log(" ", gameBoard[2][0] + " |", gameBoard[2][1] + " | " + gameBoard[2][2]);

运行修改后的代码,第二次输出时中间位置会正常显示"a",验证赋值操作成功。

内容的提问来源于stack exchange,提问作者mr.Hritik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:32:18