Add new value to an existing array in JavaScript

This question already has an answer here:

  • How to append something to an array? 25 answers

  • You don't need jQuery for that. Use regular javascript

    var arr = new Array();
    // or var arr = [];
    arr.push('value1');
    arr.push('value2');
    

    Note: In javascript, you can also use Objects as Arrays, but still have access to the Array prototypes. This makes the object behave like an array:

    var obj = new Object();
    Array.prototype.push.call(obj, 'value');
    

    will create an object that looks like:

    {
        0: 'value',
        length: 1
    }
    

    You can access the vaules just like a normal array f.ex obj[0] .


    This has nothing to do with jQuery, just JavaScript in general.

    To create an array in JavaScript:

    var a = [];
    

    Or:

    var a = ['value1', 'value2', 'value3'];
    

    To append values on the end of existing array:

    a.push('value4');
    

    To create a new array, you should really use [] instead of new Array() for the following reasons:

  • new Array(1, 2) is equivalent to [1, 2] , but new Array(1) is not equivalent to [1] . Rather the latter is closer to [undefined] , since a single integer argument to the Array constructor indicates the desired array length.
  • Array , just like any other built-in JavaScript class, is not a keyword. Therefore, someone could easily define Array in your code to do something other than construct an array.

  • Array is a JavaScript native object, why don't you just try to use the API of it? Knowing API on its own will save you time when you will switch to pure JavaScript or another framework.

    There are number of different possibilities, so, use the one which mostly targets your needs.

    Creating array with values:

    var array = ["value1", "value2", "value3"];
    

    Adding values to the end

    var array = [];
    array.push("value1");
    array.push("value2");
    array.push("value3");
    

    Adding values to the begin:

    var array = [];
    array.unshift("value1");
    array.unshift("value2");
    array.unshift("value3");
    

    Adding values at some index:

    var array = [];
    array[index] = "value1";
    

    or by using splice

    array.splice(index, 0, "value1", "value2", "value3");
    

    Choose one you need.

    链接地址: http://www.djcxy.com/p/17926.html

    上一篇: 如何将新值添加到数值数组的末尾?

    下一篇: 在JavaScript中为现有数组添加新值