In PHP, I'd do something like:
$array = array(); $array[] = "value1"; $array[] = "value2"; $array[] = "value3";
How would I do the same thing in JavaScript?
JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
To update all the elements of an array, call the forEach() method on the array, passing it a function. The function gets called for each element in the array and allows us to update the array's values. Copied! const arr = ['zero', 'one', 'two']; arr.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With