esteve
esteve

Reputation: 50

JS Array allways returns undefined and length = 0

(using Node.js) Hi, I have an array with users (User class) on it, when I print the array with console.log, it shows the content correctly and shows that it's length is 3, but when i try to get any thing from the array, it returns undefined and for *.length, it returns 0. Where's the problem?

exports.users = [];

exports.loadUsers = (callback) => {
    let more = true;
    let i = 0;
     while(more) {
		let us = _usersFolder + "us_" + i + "/";
		if(fs.existsSync(us)) {
			fs.readFile(path.join(us + "personal.json"), (err, data) => {
				if(err) {
					console.log("failed to load file!");
					return;
				}
				let json_personal = JSON.parse(data);
				this.users.push(new User(json_personal));
			});
			i++;
		} else {
			more = false;
		}
    }
    callback();
}


exports.getUserById = (id) => {
    console.log(this.users);
    console.log("length: " + this.users.length);
    console.log(this.users[0]);
	for(let i = 0; i < this.users.length; i++) {
		let u = this.users[i];
		console.log(u.id);
		if(u.id === id) {
			return u;
		}
	}
	return false;
}

getUserById is called in the callback, so users are already loaded.

enter image description here

Upvotes: 0

Views: 103

Answers (3)

Escoute
Escoute

Reputation: 396

I hope you are defining after you print in console.

var users  = [];
console.log(users);
console.log("length: " + users.length);
console.log(users[0]);
users.push(1);
users.push(2);
users.push(3);

The output of console.log() is misleading; While you log that time there was no value. After that it was added. It prints the reference of object , not the state value. So you will see current state value all the time.

Upvotes: -1

RANVIR GORAI
RANVIR GORAI

Reputation: 1286

var users=[{"num":1},{"num":2},{"num":3}];

console.log(this.users);
console.log("length: " + this.users.length);
console.log(this.users[0]);

output

(3) [Object, Object, Object]

length: 3

Object {a: 1}

Upvotes: 0

It depends on where you are using the 'this' object. It's possible that 'this' makes reference to a different object than the one you stored the array in ('this' varies depending on the scope where you are using it).

I'd need more information to help you.

Upvotes: 0

Related Questions