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

React组件复制数组调用slice时报squares.slice is not a function错误

错误原因

你的代码触发了JavaScript自动分号插入(ASI)规则的解析异常:
你声明newSquares的行末尾没有添加分号,而下一行的起始字符是括号(isX),JS引擎会将两行代码合并解析为:

const newSquares = squares.slice()(isX) ? newSquares[i] = "X" : newSquares[i]= "O"

相当于把squares.slice()的返回值当做可调用函数来执行,传入isX作为参数,但数组本身不是函数,因此抛出TypeError: squares.slice(...) is not a function错误。

修复方案

直接解决当前报错

在const newSquares = squares.slice()行末尾添加分号即可,修改后代码:

const newSquares =  squares.slice();
(isX) ? newSquares[i] = "X" : newSquares[i]= "O"

也可以将三目运算改写为if判断,彻底避免行首括号的解析问题:

const newSquares =  squares.slice()
if (isX) {
  newSquares[i] = "X"
} else {
  newSquares[i] = "O"
}

其他逻辑问题修复

你当前代码直接将棋盘数组传入了setWinner,缺少赢家判断逻辑,winner状态本应存储获胜方标识(如X/O),你可以补充如下赢家判断函数:

const calculateWinner = (squares) => {
  // 所有获胜的连线组合
  const winLines = [
    [0, 1, 2], [3, 4, 5], [6, 7, 8],
    [0, 3, 6], [1, 4, 7], [2, 5, 8],
    [0, 4, 8], [2, 4, 6]
  ]
  for (let i = 0; i < winLines.length; i++) {
    const [a, b, c] = winLines[i]
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a]
    }
  }
  return null
}

然后将onClick中的setWinner(newSquares)修改为:

const currentWinner = calculateWinner(newSquares)
setWinner(currentWinner)

内容的提问来源于stack exchange,提问作者Altair21

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:36:05