Developer deals with arrays every day. Being a collection, an important property to query is the number of items: Array.prototype.length
In JavaScript the length does not always indicate the number of existing elements (for sparse arrays) and modifying this property may remove elements. 
Let's demystify the magic behind this property.

Definition 
The length of an array is an unsigned, 32-bit integer that is numerically greater than the highest index in the array.

This property behaves differently for specific array types. Let's enumerate them: 
An array is dense when it's elements have contiguous indexes starting at 0. For example [1, 3, 4] is dense, because the indexes are contiguous: 01 and 2
An array is sparse when it's elements don't have contiguous indexes starting at 0. For example [1, , 4, 6] is sparse, because elements indexes are not contiguous: 02 and 3.

Length as the number of elements in array

The common usage of the length is to determine the number of elements. This is correct for dense collection type:

var fruits = ['orange', 'apple', 'banana']; //fruits is a dense array
fruits.length // prints 3, the real count of elements fruits.push('mango');
fruits.length // prints 4, one element was added var empty = [];
empty.length // prints 0, empty array

See the example in JS Bin

The dense array does not have empties and the number of items corresponds to highestIndex + 1. In [3, 5, 7, 8] the highest index is 3 of element 8, thus the array size is 3 + 1 = 4.

Length as a number bigger than highest index

In a sparse array the length is greater than the highest index, but it does not indicate the real number of elements. When querying length, it's bigger than elements count. It happens because of the gaps in the array.

var animals = ['cat', 'dog', , 'monkey']; // animals is sparse
animals.length // prints 4, but real number of elements is 3 var words = ['hello'];
words[6] = 'welcome'; //the highest index is 6. words is sparse
words.length //prints 7, based on highest index

When adding or removing elements, length is mutated based on the highest index only. Any array modifications that do not affect the highest index do not modify length, for example when using delete.

var colors = ['blue', 'red', 'yellow', 'white', 'black'];
colors.length // prints 5 delete colors[0]; // remove the first element 'blue'.
// The array becomes sparse colors.length // still prints 5, because the highest index 4
// wasn't modified

See the example in JS Bin

Length modification

In the previous explanations, the length was read-only. But JavaScript allows to modify this property also. 
Length modification affects the array, depending on the new value and existing highest index. It can remove elements or make the array sparse. 
When the new length number is less or equal than the highest index, any elements whose index is greater or equal than the new size are removed. An useful scenario to remove elements from the end of array.

var numbers = [1, 3, 5, 7, 8];

numbers.length = 3; // modify the array length
numbers // prints [1, 3, 5], elements 7 and 8 are removed

If using a number greater than the highest index (or using a number bigger than current length), the array will become sparse. It's rarely useful.

var osTypes = ['OS X', 'Linux', 'Windows'];

osTypes.length = 5; // creating a sparse array. Elements at indexes 3 and 4
// do not exist osTypes // prints ['OS X', 'Linux', 'Windows', , , ]

See the examples in JS Bin

It's possible to assign a different type than number to length. JavaScript will convert the primitive to a number. If the conversion result is NaN or number less than 0, an error is thrown Uncaught RangeError: Invalid array length.

var numbers = [1, 4, 6, 7];
numbers.length = '2'; // '2' is converted to number 2
numbers.length = 'not-number'; // throws Uncaught RangeError: Invalid array length
numbers.length = -2; // throws Uncaught RangeError: Invalid array length

Code safely

Modifying the array length, removing elements with delete, adding elements with [newIndex] are sources of potential problems by creating sparse arrays. And as result an inconsistent length value. 
JavaScript offers safer alternatives.

To add elements to the end of an array use Array.prototype.push() and to remove the latest pop()
To insert an element to the beginning use unshift() and to remove the first one shift()
For more complex insertions, deletions or replacements, splice() is powerful enough too.

var companies = ['Apple', 'Dell'];

companies.push('ASUS'); // Adds an element to the end
companies // prints ['Apple', 'Dell', 'ASUS'] companies.pop(); // prints "ASUS". Removes the last element
companies // prints ['Apple', 'Dell'] companies.shift(); // prints "Apple". Removes the first array element
companies // prints ["Dell"] companies.splice(1, 0, "Microsoft", "HP"); // Add 2 companies
companies // prints ["Dell", "Microsoft", "HP"] companies.length // prints 3. The array is dense

See the examples in JS Bin

There are rare situations when the array can be sparse. It's not safe to rely on the length to determine the number of elements. Just use a helper function which handles the missing elements:

/**
* Count the number of elements in a sparse array
* @param {Array} collection
* @return {number}
*/
function count(collection) {
var totalCount = 0;
for (var index = 0; index < collection.length; index++) {
if (index in collection) {
totalCount++;
}
}
return totalCount;
}

in operator determines if the object has a property. It works perfectly to check if an element exists at specific index.

Conclusion

As seen in the article, length is a property with complex behavior. 
Mostly it works without surprises, but it's better to take precautions when dealing with sparse arrays and modifying the length
An alternative is avoid at all modifying this property and use the splice() method.

Have a great coding day.

See also 
Array.prototype.length 
Sparse arrays vs dense arrays

【转】The magic behind array length property的更多相关文章

  1. Array.length vs Array.prototype.length

    I found that both the Array Object and Array.prototype have the length property. I am confused on us ...

  2. [Bug]The maximum array length quota (16384) has been exceeded while reading XML data.

    写在前面 在项目中,有客户反应无法正常加载组织结构树,弄了一个测试的程序,在日志中查看到如下信息: Error in deserializing body of reply message for o ...

  3. 缓存 Array.length 是老生常谈的小优化

    问题 缓存 Array.length 是老生常谈的小优化. // 不缓存 for (var i = 0; i < arr.length; i++) { ... } // 缓存 var len = ...

  4. check the element in the array occurs more than half of the array length

    Learn this from stackflow. public class test { public static void main(String[] args) throws IOExcep ...

  5. Count and Say (Array Length Encoding) -- LeetCode

    The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...

  6. Math.floor(Math.random() * array.length),splice

    1.Math.floor(Math.random() * array.length) 返回长度内的索引 eg: changeLimit () { function getArrayItems(arr, ...

  7. javascript change array length methods

    javascript change array length methods Array 改变数组长度的方法 push, pop shift, unshift, splice, fill, 不改变数组 ...

  8. Swift String length property

    Swift的String居然没有length属性,好难受,每次要获取String的字符串长度都要借助全局函数countElements. 没办法.仅仅有扩展String结构体,给它加入一个属性了. i ...

  9. how to increase an regular array length in java?

    Arrays in Java are of fixed size that is specified when they are declared. To increase the size of t ...

随机推荐

  1. win8.1去掉鼠标右键回收站“固定到开始”屏幕的方法

    平台:win8.1 问题:桌面“回收站”右键菜单里有个“固定到开始屏幕”,一不小心就误按,设法删除之. 打开注册表编辑器.在注册表编辑器里面定位到:HKEY_LOCAL_MACHINE\SOFTWAR ...

  2. sql语句-排序后加入序号再运算判断取想要的项

    select a.id as aid,b.id as bid,a.city,a.cang,a.sid,a.time as atime,b.time as btime,a.price as aprice ...

  3. 《Java Mail》

    <Java Mail> 文/冯皓林 完稿:2016.3.16--2016.3.19 “特定环境.一类问题.N个解决方案” 一.RFC821文档说明 核心: 邮件(Mail): 1.邮件头( ...

  4. STM32F207 两路ADC连续转换及GPIO模拟I2C给MT9V024初始化参数

    1.为了更好的方便调试,串口必须要有的,主要打印一些信息,当前时钟.转换后的电压值和I2C读出的数据. 2.通过GPIO 模拟I2C对镁光的MT9V024进行参数初始化.之前用我以前公司SP0A19芯 ...

  5. 【伪一周小结(没错我一周就做了这么点微小的工作)】HDOJ-1241 Oil Deposits 初次AC粗糙版对比代码框架重构版

    2016 11月最后一周 这一周复习了一下目前大概了解的唯一算法--深度优先搜索算法(DFS).关于各种细节的处理还是极为不熟练,根据题意判断是否还原标记也无法轻松得出结论.不得不说,距离一个准ACM ...

  6. HttpCookie类

    转自:http://www.cnblogs.com/kissdodog/archive/2013/01/08/2851937.html HttpCookie类专门由C#用于读取和写入Cookie的类. ...

  7. 不注册COM组件直接调用接口

    本文以COM组件AppTest.dll为例,AppTest.dll中提供了ITest接口,在不使用regsvr32命令向系统注册的情况下创建ITest接口并调用. 一.导入组件或类型库: 在C++中使 ...

  8. sql查询百分号的方法

    select * from [tablename] where [col] like '%100/%%' escape '/'

  9. 【经典dp】 poj 3671

    开一个dp[30010][3]的数组 其中dp[i][j]表示把第i个数改成j最少要花多少次 那么状态转移方程就列出来了: 令a=1 j!=a[i] 0 j==a[i] 那么dp[i][1]=dp[i ...

  10. 关于C#静态构造函数的几点说明

    静态构造函数是C#的一个新特性,其实好像很少用到.不过当我们想初始化一些静态变量的时候就需要用到它了.这个构造函数是属于类的,而不是属于哪里实例的,就是说这个构造函数只会被执行一次.也就是在创建第一个 ...