数组splice创建一个空白数组。

时间:2022-07-23 19:35:29

I have the following react code

我有以下的反应代码

     constructor(props) {
        super(props);
        this.state = {registrations: [{firstName: "foo", lastName: "bar", activity: "Science Lab", restrictions: "a,b,c"}]}
     }
     addRegistration(registration) {
        console.log('came inside event handler to add registration')
        console.log(registration)
        console.log('existing state')
        console.dir(this.state.registrations)            
        var newState = this.state.registrations.splice() // copy
        console.dir(newState)
        newState.push(registration)
        console.log(newState)
        this.setState({registrations: newState})
    }

when I run my code and the addRegistration event handler is called I see the following output

当我运行代码并调用addRegistration事件处理程序时,我将看到以下输出

[Log] {firstName: "Foo", lastName: "Bar", activity: "Swimming", restrictions: "a,b"} (Registration.html, line 404)
[Log] existing state (Registration.html, line 405)
[Log] [Object] (1) (Registration.html, line 406)
[Log] [] (0) (Registration.html, line 408)
[Log] [Object] (1) (Registration.html, line 410)

so I get a valid registration object as input parameter. In the 3rd entry of the log we see that the existing state had an array of size 1. (which is the foo object from the constructor

我得到一个有效的注册对象作为输入参数。在日志的第3项中,我们看到现有状态的数组大小为1。它是构造函数中的foo对象

next we see that the call to this.state.registrations.splice() created and empty array. and then the new registration object received as parameter is pushed into the empty created thereby creating another Array of size 1.

接下来,我们将看到对this.state.registration .splice()的调用创建了并且是空数组。然后将作为参数接收的新注册对象推入创建的空中,从而创建另一个大小为1的数组。

I don't understand why splice() created an empty array. it should have returned me a copy of the existing state and then the push should have resulted in an array size of 2.

我不明白为什么splice()创建了一个空数组。它应该返回一个现有状态的副本,然后push应该会导致数组大小为2。

what did I miss?

我错过了什么?

1 个解决方案

#1


4  

splice return you the array of deleted elements, whereas slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). you can create a copy of array by using spread operator syntax or using slice like

splice会返回已删除元素的数组,而slice()方法将数组的一部分的浅拷贝返回到一个从start到end (end不包括在内)选择的新数组对象中。您可以通过使用扩展操作符语法或使用slice来创建数组的副本。

var newState = this.state.registrations.slice() 

or

var newState = [...this.state.registrations]

#1


4  

splice return you the array of deleted elements, whereas slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). you can create a copy of array by using spread operator syntax or using slice like

splice会返回已删除元素的数组,而slice()方法将数组的一部分的浅拷贝返回到一个从start到end (end不包括在内)选择的新数组对象中。您可以通过使用扩展操作符语法或使用slice来创建数组的副本。

var newState = this.state.registrations.slice() 

or

var newState = [...this.state.registrations]