【问题标题】:What’s a way to append a value to an array? [duplicate]将值附加到数组的方法是什么? [复制]
【发布时间】:2014-05-02 06:02:27
【问题描述】:

追加到数组

如何在 Javascript 中追加到数组

【问题讨论】:

  • 调用 push()。 var a=[];a.push(1);
  • 这个问题似乎离题了,因为它是关于在谷歌上搜索 OP 的“JavaScript Array Append”。
  • 我的 google down 或 SO 的搜索工具不起作用?好的

标签: javascript arrays


【解决方案1】:

创建一个新数组。

var fruits = ["Banana", "Orange", "Apple", "Mango"];

然后像这样推送值

fruits.push("Kiwi");

【讨论】:

    【解决方案2】:

    你可以这样做:

    // create a new array, using the `literals` instead of constructor
    var array = [];
    
    // add a value to the last position + 1 (that happens to be array.length) 
    array[array.length] = 10;
    

     // use the push method from Array.
     array.push(10);
    

    另外,如果你有一个对象并且你希望它表现得像一个数组(不推荐),你可以使用

    Array.prototype.push.call(objectLikeArray, 10);
    

    【讨论】:

      猜你喜欢
      • 2015-02-23
      • 2011-11-21
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2013-05-09
      • 2014-12-17
      • 2021-07-03
      • 2022-08-20
      相关资源
      最近更新 更多