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];
}
Mamun
  • 66,969
  • 9
  • 47
  • 59
Jay
  • 187
  • 2
  • 13
  • 7
    Use `()` on push. Like `result.push(i)`; – Eddie Oct 17 '18 at 10:02
  • What exactly are you trying to do? `result.push[i]` does not do anything. – Jerodev Oct 17 '18 at 10:03
  • Why doesn't `push[i]` return an error BTW? I'm curious – DarkBee Oct 17 '18 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`. – nicholaswmin Oct 17 '18 at 11:38
  • @NicholasKyriakides Thank you for that insight :) – DarkBee Oct 17 '18 at 11:39
  • 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);` – Jay Oct 17 '18 at 12:01
  • @Jaykumar - Please [edit](https://stackoverflow.com/posts/52852179/edit) your question to provide more updates/clarifications – DarkBee Oct 17 '18 at 13:54

4 Answers4

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?

Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
  • 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);` – Jay Oct 17 '18 at 11:37
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);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Please use the below code:

var result = [];      
for (var i=0; i < 10; i++) {      
    result.push(i);      
}
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)