最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Can javascript add element to an array without specifiy the key like PHP? - Stack Overflow

programmeradmin0浏览0评论

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
  • 2 you can use array.push to Push elements onto an array without specifying the index – Hanky Panky Commented Jan 28, 2013 at 6:45
  • see this – mamdouh alramadan Commented Jan 28, 2013 at 6:45
  • Oh, you mean if there is a javascript equivalent to PHPs array_push ;) – lll Commented Jan 28, 2013 at 8:39
Add a comment  | 

5 Answers 5

Reset to default 16

Simply 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.

发布评论

评论列表(0)

  1. 暂无评论