JavaScript 在对象中创建数组并将数据推送到数组

IT技术 javascript arrays object reactjs push
2021-04-30 05:23:01

我是编程新手。我正在尝试 React 并具有函数 addComment,该函数在用户向新闻添加评论时执行。此时我需要创建一个属性评论(数组)并分配或推送到该数组的inputCommentValue值。但是现在我只重写了数组的 0 个元素,无法添加新元素。你能告诉我把push方法放在哪里吗?谢谢!

var ARTICLES = [{
  title: "sit amet erat",
  text: "nam dui proin leo odio porttitor id consequat in consequat ut nulla sed accumsan"

}, {
  title: "pulvinar sed",
  text: "velit id pretium iaculis diam erat fermentum justo nec condimentum"
}]



addComment(index, inputCommentValue){
ARTICLES = [...ARTICLES], ARTICLES[index].comments=[inputCommentValue];
this.setState({ARTICLES:ARTICLES});
}
2个回答

假设您有一个这样的对象。

   foo : {
       bar : "x"
    }

要创建一个数组,只需将其初始化为一个空数组。

foo.newArray = []

如果你console.log(foo),你现在会看到这个

foo : {
   bar : "x",
   newArray : []
 }

这意味着您的foo对象有一个名为newArray. 您可以使用该push()方法向其中添加元素

像这样推送一个变量 像这样foo.newArray.push(myVariable); 推送一个字符串 像这样foo.newArray.push("myString"); 推送一个对象

 foo.newArray.push({
    "bar2" : "val2"
 });

有关数组的更多信息,请查看W3schools

在您的特定情况下,只需执行 ARTICLES.push({})

假设数据存在于组件的 state 中,那么处理程序看起来像这样

addComment(index, inputCommentValue){
    // copy array , for not mutate state
    let ARTICLES = [...this.state.ARTICLES];
    // check if comments not exist
    if(!ARTICLES[index].comments) ARTICLES[index].comments=[];
    // add new comment to array
    ARTICLES[index].comments.push(inputCommentValue);
    // update component with new articles
    this.setState({ARTICLES:ARTICLES});
}