In PHP , I can add a value to the array like this:
array[]=1;
array[]=2;
and the output will be 0=>'1', 1=>'2';
And if I tried the same code in javascript , it return Uncaught SyntaxError: Unexpected string . So , is there any way in JS to work the same as PHP? Thanks
In PHP , I can add a value to the array like this:
array[]=1;
array[]=2;
and the output will be 0=>'1', 1=>'2';
And if I tried the same code in javascript , it return Uncaught SyntaxError: Unexpected string . So , is there any way in JS to work the same as PHP? Thanks
Share Improve this question edited Jan 28, 2013 at 6:45 Rab 35.6k4 gold badges51 silver badges66 bronze badges asked Jan 28, 2013 at 6:43 user782104user782104 13.6k60 gold badges178 silver badges315 bronze badges 3 |5 Answers
Reset to default 16Simply use Array.push
in 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
Programmatically, you simply "push" an item in the array:
var arr = [];
arr.push("a");
arr.push("b");
arr[0]; // "a";
arr[1]; // "b"
You cannot do what you're suggesting:
arr[] = 1
is not valid JavaScript.
For special cases You can use next (without .push()):
var arr = [];
arr[arr.length] = 'foo';
arr[arr.length] = 'bar';
console.log(arr); // ["foo", "bar"]
From w3schools
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction()
{
fruits.push("Kiwi")
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script>
I wanted to find a way to add a value as an array element to a variable or property, when such doesn't exist yet. (Much like php's $var[] = 'foo'.) So I asked around, and this is what I learned.
Variable:
var arr;
(arr = arr || []).push('foo');
Property:
var obj = {};
(obj.arr = obj.arr || []).push('foo');
|| returns the left side if it's true, and the right side if the left is false. By the time .push() executes, arr is an array--if it wasn't already.
array_push
;) – lll Commented Jan 28, 2013 at 8:39