[英]How to add element in array using functions with javascript
I'm trying to add element using javascript in array but I couldn't add more than one element for example 我正在尝试使用javascript在数组中添加元素,但是我不能添加多个元素
var myArr = []; function Items(content) { myArr.push(content); } Items("item1", "item2", "item3");
or something like that 或类似的东西
var myArr = []; function Items(content){ for(var i=0;i<myArr.length;i++){ myArr.push(content); } } Items("item1","item2","item3");
it returns empty. 它返回空。
How do i add element in array with javascript using functions ? 如何使用函数使用javascript在数组中添加元素?
Your first example is correct as far as it goes, but since you're passing multiple arguments, you need to declare multiple parameters to receive them in, and use them: 您的第一个示例就目前而言是正确的,但是由于要传递多个参数,因此需要声明多个参数以接收它们并使用它们:
var myArr = []; function Items(item1, item2, item3) { // *** Note parameters myArr.push(item1, item2, item3); // *** Using them } Items("item1", "item2", "item3"); console.log(myArr);
Alternately, you could pass in an array: 或者,您可以传递一个数组:
var myArr = []; function Items(items) { // ES2015+ spread notation myArr.push(...items); // Or ES5 and earlier: // myArr.push.apply(myArr, items); } Items(["item1", "item2", "item3"]); // ^-------------------------^---- note passing in an array console.log(myArr);
More about spread notation here . 更多有关传播符号的信息 。
If you want to accept discrete arguments of any length, in ES2015+ you'd use a rest parameter : 如果您想接受任意长度的离散参数,请在ES2015 +中使用rest参数 :
var myArr = []; function Items(...items) { myArr.push(...items); } Items("item1", "item2", "item3"); console.log(myArr);
In ES5 and earlier, you'd use arguments
: 在ES5和更早的版本中,您将使用
arguments
:
var myArr = []; function Items() { myArr.push.apply(myArr, arguments); } Items("item1", "item2", "item3"); console.log(myArr);
You are only pushing the first argument content
which represents "item1"
, you need to pass all the arguments (you can use the reserved keyword arguments
to access all the passed arguments), if you are using ES6 you can just use myArr.push(...arguments)
, if not you can use the following code: 您只需要推送代表
"item1"
的第一个参数content
,就需要传递所有参数(可以使用保留的关键字arguments
来访问所有传递的参数),如果您使用的是ES6,则可以使用myArr.push(...arguments)
,如果没有,则可以使用以下代码:
var myArr = []; function Items(){ myArr.push.apply(myArr, arguments); } Items("item1","item2","item3"); console.log(myArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.