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 ?
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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.