JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

7.4 Array Length

Understanding sparse arrays is an important part of understanding the true nature of JavaScript arrays. In practice, however, most JavaScript arrays you will work with will not be sparse. And, if you do have to work with a sparse array, your code will probably treat it just as it would treat a nonsparse array with undefined elements.

7.4 Array Length

Every array has a length property, and it is this property that makes arrays different from regular JavaScript objects. For arrays that are dense (i.e., not sparse), the length property specifies the number of elements in the array. Its value is one more than the highest index in the array:

[].length // => 0: the array has no elements

['a','b','c'].length // => 3: highest index is 2, length is 3

When an array is sparse, the length property is greater than the number of elements, and all we can say about it is that length is guaranteed to be larger than the index of every element in the array. Or, put another way, an array (sparse or not) will never have an element whose index is greater than or equal to its length. In order to maintain this invariant, arrays have two special behaviors. The first was described above: if you assign a value to an array element whose index i is greater than or equal to the array’s current length, the value of the length property is set to i+1.

The second special behavior that arrays implement in order to maintain the length invariant is that if you set the length property to a non-negative integer n smaller than its current value, any array elements whose index is greater than or equal to nare deleted from the array:

a = [1,2,3,4,5]; // Start with a 5-element array.

a.length = 3; // a is now [1,2,3].

a.length = 0; // Delete all elements. a is [].

a.length = 5; // Length is 5, but no elements, like new Array(5)

You can also set the length property of an array to a value larger than its current value. Doing this does not actually add any new elements to the array, it simply creates a sparse area at the end of the array.

In ECMAScript 5, you can make the length property of an array read-only with Object.defineProperty() (see §6.7 ): a = [1,2,3]; // Start with a 3-element array. Object.defineProperty(a, "length", // Make the length property {writable: false}); // readonly. a.length = 0; // a is unchanged.

Similarly, if you make an array element nonconfigurable, it cannot be deleted. If it cannot be deleted, then the length property cannot be set to less than the index of the nonconfigurable element. (See §6.7 and the Object.seal() and Object.freeze() methods in §6.8.3 .)

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1