javascript javascript可以像PHP那样在没有指定键的情况下将元素添加到数组中吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14556760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:58:30  来源:igfitidea点击:

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

phpjavascriptarrays

提问by user782104

In PHP , I can add a value to the array like this:

在 PHP 中,我可以像这样向数组添加一个值:

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

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

输出将是 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

如果我在 javascript 中尝试相同的代码,它会返回Uncaught SyntaxError: Unexpected string。那么,在 JS 中有什么方法可以像 PHP 一样工作吗?谢谢

回答by MarcDefiant

Simply use Array.pushin javascript

只需Array.push在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

MDN 上的 Array.push

回答by krisk

Programmatically, you simply "push" an item in the array:

以编程方式,您只需“推送”数组中的一个项目:

var arr = [];

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

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

You cannotdo what you're suggesting:

不能按照你的建议去做:

arr[] = 1

is notvalid JavaScript.

不是有效的JavaScript。

回答by Александр Чертков

For special cases You can use next (without .push()):

对于特殊情况,您可以使用 next(不带 .push()):

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

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

回答by Amaroq

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.

我想找到一种方法,将一个值作为数组元素添加到变量或属性中,当这样的值尚不存在时。(很像 php 的 $var[] = 'foo'。)所以我四处打听,这就是我学到的。

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.

|| 如果为真则返回左侧,如果左侧为假则返回右侧。到 .push() 执行时, arr 是一个数组——如果它还没有的话。

回答by mamdouh alramadan

From w3schools

来自w3schools

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

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