3

I want to access array variable outside the loop. but its returning null. below is sample code.

var result = [];
for (var i=0; i < 10; i++) {
     result.push[i];
}

7
  • 7
    Use () on push. Like result.push(i); Commented Oct 17, 2018 at 10:02
  • What exactly are you trying to do? result.push[i] does not do anything. Commented Oct 17, 2018 at 10:03
  • Why doesn't push[i] return an error BTW? I'm curious Commented Oct 17, 2018 at 10:04
  • @DarkBee because a function is an object in JS. array.push[2] = 'foo' creates a property 2 on the push method with value foo. Commented Oct 17, 2018 at 11:38
  • @NicholasKyriakides Thank you for that insight :) Commented Oct 17, 2018 at 11:39

4 Answers 4

3

The syntex of push method is push() not push[].

var result = [];
for (var i=0; i < 10; i++) {
    result.push(i);
}
console.log(result);

For more info about push() look How to append something to an array?

Sign up to request clarification or add additional context in comments.

1 Comment

actually want achieve below code var args ={},fileObject = []; for (var i in files) { base64.encode('/opt/zipoutput/' + files[i], function (err, base64String) { convertval = base64String; var dataObj = { "actions": [ { "file_path": files[i] }] }; fileObject.push(dataObj); }); } console.log("fileObject111-----",fileObject);
1

push is a method implemented on array. The basic syntax of invoking or calling a function is to specify parenthesis () after the function name.

Array.prototype.push()

The push() method adds one or more elements to the end of an array and returns the new length of the array.

var result = [];
for (var i=0; i < 10; i++) {
     result.push(i);
}
console.log(result);

Comments

0

Please use the below code:

var result = [];      
for (var i=0; i < 10; i++) {      
    result.push(i);      
}

Comments

0

You can do that like this also.

var result = [];
    for (var i=0; i < 10; i++) {
         result[i]=i;
    }

If you want to use push then use like this result.push(i)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.