Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Length returns 0

Could anyone help explain why length is returning 0? Thank you VERY much in advance!

var errors = [];
errors[''] = "Monday Morning slot already taken. Would you like to replace it?";
console.log(errors);
document.write(errors.length);
like image 794
Justin Harris Avatar asked Jan 25 '14 22:01

Justin Harris


2 Answers

Only numeric indices affect the .length of an Array.

Other named properties are allowed, but they aren't the typical use for an Array object. By using "", you're creating a non-numeric property on the object. You can access it like this:

errors[""];

But you can't get to it with the typical Array methods.


For named properties, you'd typically use an Object instead. Either way, you can get a count of the number of own, enumerable properties (including numeric indices) by using Object.keys().

Object.keys(errors).length;
like image 124
cookie monster Avatar answered Oct 17 '22 12:10

cookie monster


Because that is not how you add an item since Arrays only accept numeric keys. You do it like this:

errors.push("blah");  /*or*/  errors[0] = "blah";

//Now if you check the length:
errors.length;  //1

Also, if you are using it as an Object, '' isn't a valid name either.

*Correction: Looks like you can use "" (empty string) as a key.

like image 11
Derek 朕會功夫 Avatar answered Oct 17 '22 14:10

Derek 朕會功夫