【问题标题】:push method not returning new array推送方法不返回新数组
【发布时间】:2018-12-26 10:10:59
【问题描述】:

我正在通过 javascript push() 方法将对象添加到数组中。我的数组是一个对象数组。我想 console.log() 新数组。但它给了我新数组的长度。我知道 push() 方法返回新数组的长度,但我想在我的应用程序中使用新数组。如何获得它

    let sub_sprite = this.state.sub_sprite;
    let updated_sub_subsprite;
    updated_sub_subsprite = sub_sprite.push(this.state.sprite[that.state.sprite_count]);
    console.log(updated_sub_subsprite);

    that.setState({sub_sprite:updated_sub_subsprite}, ()=>{
         console.log(this.state.sub_sprite)
    });

【问题讨论】:

  • 你的控制台说什么?
  • 使用Array.prototype.concat。见concat

标签: javascript reactjs


【解决方案1】:

不要在存储在 React 组件状态中的数组上使用 Array.push,它会直接改变状态,这可能会导致问题 (see this article)。

您可以使用Array.concat 创建一个带有附加值的新数组:

let sub_sprite = this.state.sub_sprite
let updated_sub_subsprite;
updated_sub_subsprite = sub_sprite.concat([this.state.sprite[that.state.sprite_count]]);
console.log(updated_sub_subsprite);
that.setState({sub_sprite:updated_sub_subsprite}, ()=> {
    console.log(this.state.sub_sprite)
})

更简洁方便的方法是使用spread syntax(注意三个点):

let sub_sprite = this.state.sub_sprite
let updated_sub_subsprite;
updated_sub_subsprite = [...sub_sprite, this.state.sprite[that.state.sprite_count]);
console.log(updated_sub_subsprite);
that.setState({sub_sprite:updated_sub_subsprite}, ()=> {
    console.log(this.state.sub_sprite)
})

【讨论】:

    【解决方案2】:

    Array#push 方法不会返回新数组,而是在将项目添加到该数组实例后返回 the length of the array

    看起来Array#concat 方法更适合您正在尝试做的事情,seeing that offers the "appending behavior" 并且还返回结果数组。

    考虑对您的代码进行以下调整,利用concat() 来实现您想要的:

    let sub_sprite = this.state.sub_sprite;
    
    // Create a new array via concat(), adding a new array with one item 
    // that is [ sub_sprite [that.state.sprite_count] ] to sub_sprite
    let updated_sub_subsprite = sub_sprite.concat( [ sub_sprite [that.state.sprite_count] ]);
    
    console.log(updated_sub_subsprite);
    
    that.setState({sub_sprite : updated_sub_subsprite }, ()=>{
        console.log(this.state.sub_sprite)
    })
    

    【讨论】:

      猜你喜欢
      • 2012-06-27
      • 2017-05-29
      • 2021-08-15
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 2020-11-16
      • 2016-07-23
      • 2023-03-23
      相关资源
      最近更新 更多