React 官方实例中,计算九宫格胜者的判定用for循环就可以,用es5语法的forEach就不行,这是为什么?

实例地址: https://codepen.io/gaearon/pe...

// 使用forEach就不行
lines.forEach(item=>{
        const [a,b,c] = item
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]){
            console.log(squares[a])
            return squares[a]
        }
    })
    // 官方示例用的for循环
    // for (let i = 0; i < lines.length; i++) {
    //     const [a, b, c] = lines[i];
    //     if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
    //         return squares[a];
    //     }
    // }

使用for循环来判断胜者条件就可以成功,使用forEach就不行,打印forEach return有值

const winner = calculateWinner(this.state.squares)
        let status
        if (winner){
            status = 'Winner:'+ winner
        } else {
            status = 'Next player: '+(this.state.xIsNext?'X':'O')
        }

但是后面的winner一直拿不到这个return的值,一直为null.是forEach中return有问题?

阅读 2.3k
1 个回答

forEach不能返回值而且不能中断

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题