Can javascript add an element to an array without specifying a key such as PHP?

In PHP, I can add a value to the array as follows:

array[]=1;
array[]=2;

and the output will be 0=>'1', 1=>'2';

And if I tried the same code in javascript, it returns Uncaught SyntaxError: Unexpected string. So, is there a way in JS to work just like PHP? Thanks

+5
source share
5 answers

Just use Array.pushin javascript

var arr = [1,2,3,4];

// append a single value
arr.push(5);  // arr = [1,2,3,4,5]

// append multiple values
arr.push(1,2) // arr = [1,2,3,4,5,1,2]

// append multiple values as array
Array.prototype.push.apply(arr, [3,4,5]); // arr = [1,2,3,4,5,1,2,3,4,5]

Array.push on MDN

+12
source

Programmatically, you simply "push" an element in an array:

var arr = [];

arr.push("a");
arr.push("b");

arr[0]; // "a";
arr[1]; // "b"

You cannot do what you offer:

arr[] = 1

not valid javascript.

+3
source

w3schools

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

function myFunction()
{
fruits.push("Kiwi")
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script>
0

, . ( php $var [] = 'foo'.) , , .

var arr;
(arr = arr || []).push('foo');

:

var obj = {};
(obj.arr = obj.arr || []).push('foo');

|| returns the left side if true, and the right side to the left. By the time of execution .push () arr is an array - if it was not already.

0
source

In special cases, you can use the following (without .push ()):

var arr = [];
arr[arr.length] = 'foo';
arr[arr.length] = 'bar';

console.log(arr); // ["foo", "bar"]
0
source

All Articles