Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access array data in Javascript

I am still very new to programming and javascript. The problem I am facing now is I am not able to access the data inside array. Here is my code snippet

global.arr = [];
var id = 12;

for (var i=0; i<5; i++) {
   arr.push(id);
   id++;
}
console.log(arr);
console.log(arr[0]);

this is the console image

My question is that, how can I access into the data and what did i do wrong here?


Here is the code I currently have, it still doesn't seem to work:

var arr = [];
var id = 12;

for (var i=0; i<5; i++) {
   arr.push(id);
   id++;
}
console.log(arr);
console.log(arr[0]);
like image 959
Emilylaw Avatar asked Dec 14 '22 16:12

Emilylaw


1 Answers

Edit: Expanding this a little more:

global is not a JavaScript object. There are global objects, but you access them through window not global. Your code would only work if you had, somewhere else, set global equal to window.

Unless you have a really good reason to use global (or window for that matter), just define the array (and other variables) with var or let.

let arr = [];
let id = 12;

for (let i=0; i<5; i++) {
   arr.push(id);
   id++;
}
console.log(arr);
console.log(arr[0]);
like image 117
Kurt Avatar answered Dec 16 '22 06:12

Kurt