简体   繁体   English

Javascript中的数组长度

[英]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 我绝对是编程和Javascript的初学者,并且正在观看道格拉斯·克罗克福德的一部视频,他说以下内容

Arrays unlike objects have a special length member 与对象不同的数组具有特殊的长度成员

It is always 1 larger than the highest integer subscript 它总是比最高整数下标大1

In this array 在这个数组中

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

a.length equals to 7. a.length等于7。

So I am not quite sure what 1 larger than highest integer subscript means...? 因此,我不太确定比最大整数下标大1意味着什么? Is it just an outdated piece of info from a older version of Javascript or am i missing something ? 这只是旧版Javascript中过时的信息,还是我缺少什么?

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). length等于数组中的元素个数,并且索引从0开始,理解它就好像您不是从1而是从0开始,所以您的元素比length(length)小1。 so 所以

length = total elements 长度=总元素

and

last index = length-1; 最后一个索引= length-1;

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

It just means that the length of an array is always * its largest index + 1. 这仅表示数组的长度始终为 *其最大索引+ 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 *实际上并非总是如此,例如,当您使用带有数字参数的Array构造函数时: var a = new Array(5) ,该数组为空,但是其length明确设置为5

Indexes and lengths are different. 索引和长度不同。 While a JavaScript array will start at 0, the length will always be the true number. 虽然JavaScript数组将从0开始,但长度始终是真实数字。 This is helpful since on a slice, the last number is NOT inclusive. 这很有用,因为在切片中,最后一个数字不包含在内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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