-1

I'm trying to add element using javascript in array but I couldn't add more than one element for example

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 ?

ani_css
  • 2,118
  • 3
  • 30
  • 73
  • You will have to iterate over the content and not the array you want to insert to. Furthermore if you want to use your function that way you'll have to use variable parameters like shown here http://stackoverflow.com/questions/1959040/is-it-possible-to-send-a-variable-number-of-arguments-to-a-javascript-function – derpirscher Aug 18 '18 at 11:31

2 Answers2

1

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:

var myArr = [];
function Items(...items) {
  myArr.push(...items);
}

Items("item1", "item2", "item3");
console.log(myArr);

In ES5 and earlier, you'd use arguments:

var myArr = [];
function Items() {
  myArr.push.apply(myArr, arguments);
}

Items("item1", "item2", "item3");
console.log(myArr);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

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:

var myArr = [];
function Items(){
    myArr.push.apply(myArr, arguments);
}

Items("item1","item2","item3");
console.log(myArr);
Ahmed Agiza
  • 360
  • 1
  • 7