惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Vulnerabilities – Threatpost
云风的 BLOG
云风的 BLOG
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
I
Intezer
Scott Helme
Scott Helme
A
About on SuperTechFans
博客园 - 司徒正美
Hacker News: Ask HN
Hacker News: Ask HN
The GitHub Blog
The GitHub Blog
Forbes - Security
Forbes - Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
S
Security Affairs
宝玉的分享
宝玉的分享

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
The Magic Behind Array Length Property
Dmitri Pavlutin · 2016-01-17 · via Dmitri Pavlutin Blog

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.

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: 0, 1 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: 0, 2 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.

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