Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...