简体   繁体   中英

Array Length in Javascript

I am an absolute beginner to programming and Javascript and was watching one of Douglas crockford's videos where he says the following

Arrays unlike objects have a special length member

It is always 1 larger than the highest integer subscript

In this array

var a = [1,2,3,4,5,6,7]

a.length equals to 7.

So I am not quite sure what 1 larger than highest integer subscript means...? Is it just an outdated piece of info from a older version of Javascript or am i missing something ?

length equals to no of elements in the array and index starts from 0 , understand it like you are not starting with 1 instead with 0 so you will have 1 less than total elements(length). so

length = total elements

and

last index = length-1;

数组从0(第一个元素)开始索引,但长度从1(一个元素)开始(如果没有元素,则数组的长度为-1,如果没有元素,则长度为0;如果有2个元素,第二个元素的索引为1,长度为2)。

It just means that the length of an array is always * its largest index + 1.

Consider:

var a = [];
a[6] = 'foo';
console.log(a.length) //7
a[20] = 'bar';
console.log(a.length) //21

*actually not always, like for example when you use Array constructor with number argument: var a = new Array(5) , the array is empty, but it has its length explicitely set to 5

Indexes and lengths are different. While a JavaScript array will start at 0, the length will always be the true number. This is helpful since on a slice, the last number is NOT inclusive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM