为什么初始化1D数组和2D数组以在React js中声明的行为不同

例子1

const arr   = ["a","b","c","d"]

class Alphabate extends React.Component{
    constructor(props){
        super(props)
        this.state = {alpha:[...arr]}
        this.state.alpha[0] = "Changed"
        console.log(`inside consructor arr =  ${arr}`)
        
    }

    render(){
        return <div>
            {this.state.alpha.map(
            x=><h3>{x}</h3>
            )}
             </div>
    }
}



ReactDOM.render(<Alphabate />,
document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>

在此示例中,显示了1个浏览器 已变更 b C d 和控制台日志“内部构造函数arg = a,b,c,d”

const arr   = [["a","b"],
               ["c","d"]]

class Alphabate extends React.Component{
    constructor(props){
        super(props)
        this.state = {alpha:[...arr]}
        this.state.alpha[0][0] = "Changed"
        console.log(`inside consructor arr =  ${arr}`)
        
    }

    render(){
        return <div>
            {this.state.alpha.map(
            x=>x.map(
            y=><h3>{y}</h3>
            ))}
             </div>
    }
}



ReactDOM.render(<Alphabate />,
document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>

在此示例中,浏览器显示 已变更 b C d 和控制台日志“内部构造器arr =已更改,b,c,d”

所以我的问题是:尽管我已经传递了数组[... arr]而不是数组的副本,但为什么1D数组按值传递而2D数组按引用传递

评论
  • equia
    equia 回复

    JavaScript没有“ 2d”数组。它具有数组的数组。执行此操作时:

    this.state = {alpha:[...arr]}
    

    ...you're only making a copy of the outer array; it still contains references to the same inner arrays that the original arr had. So when you change the contents of those inner arrays, you see that change regardless of which outer array you look through to get to the inner one.