Difficulties in JavaScript array operations (detailed tutorial)

亚连
Release: 2018-06-20 13:56:30
Original
2071 people have browsed it

This article explains the difficulties of JavaScript array operations and what needs to be paid attention to by giving examples of code analysis. Let's study and refer to it together.

The following content is the experience summarized when learning JavaScript arrays and the points that need to be paid attention to.

Don’t use for_in to traverse arrays

This is a common misunderstanding among JavaScript beginners. for_in is used to traverse all enumerable (enumerable) keys in the object including the prototype chain. It does not originally exist for traversing arrays.

There are three problems with using for_in to traverse arrays:

1. The traversal order is not fixed

The JavaScript engine does not guarantee the traversal order of objects. When traversing an array as a normal object, the index order of the traversal is also not guaranteed.

2. The values on the object prototype chain will be traversed.

If you change the prototype object of the array (such as polyfill) without setting it toenumerable: false, for_in will iterate over these things.

3. Low operating efficiency.

Although theoretically JavaScript uses the form of objects to store arrays, the JavaScript engine is particularly optimized for arrays, a very commonly used built-in object. https://jsperf.com/for-in-vs-...
You can see that using for_in to traverse an array is more than 50 times slower than using subscripts to traverse an array

PS: You may want to Find for_of

Don’t use JSON.parse(JSON.stringify()) to deep copy arrays

Some people use JSON to deep copy objects or arrays. Although this is a simple and convenient method in most cases, it may also cause unknown bugs because: some specific values will be converted tonull

NaN, undefined, Infinity for JSON that is not These supported values will be converted to null when serializing JSON. After deserialization, they will naturally be null

Key-value pairs with undefined values will be lost

When serializing JSON Keys with undefined values will be ignored and will naturally be lost after deserialization.

Will convert the Date object into a string

JSON does not support object types. For Date objects in JS The processing method is to convert it into a string in ISO8601 format. However, deserialization does not convert the time format string into a Date object

The operation efficiency is low.

As native functions,JSON.stringifyandJSON.parseoperate on JSON strings very quickly. However, it is completely unnecessary to serialize the object to JSON and deserialize it back in order to deep copy the array.

I spent some time writing a simple function for deep copying arrays or objects. The test found that the running speed is almost 6 times that of using JSON transfer. By the way, it also supports the copying of TypedArray and RegExp objects

https://jsperf.com/deep-clone...

Don’t use arr.find instead of arr.some

Array.prototype.findis a new array search function in ES2015, which is similar toArray.prototype.some, but cannot replace the latter.

Array.prototype.findReturns the first qualified value, directly use this value to doifto determine whether it exists. If this qualified value happens to be 0 What to do?

arr.findis to find the value in the array and then further process it. It is generally used in the case of object array;arr.someis to check the existence; The two cannot be mixed.

Don’t use arr.map instead of arr.forEach

is also a mistake that JavaScript beginners often make. They often don’t distinguish betweenArray.prototype.mapand ## The actual meaning of #Array.prototype.forEach.

mapis calledMAPin Chinese. It derives another new sequence by executing a certain function on a certain sequence in sequence. This function usually has no side effects and does not modify the original array (so-called pure function).

forEachThere are not so many explanations. It simply processes all items in the array with a certain function. SinceforEachhas no return value (returns undefined), its callback function usually contains side effects, otherwise thisforEachis meaningless.

It is true that

mapis more powerful thanforEach, butmapwill create a new array and occupy memory. If you don't use the return value ofmap, then you should useforEach

Supplement: experience supplement

ES6 previous , there are two main methods for traversing an array: handwritten loop iteration using subscripts, and using

Array.prototype.forEach. The former is versatile and the most efficient, but it is more cumbersome to write - it cannot directly obtain the values in the array.

The author personally likes the latter: you can directly obtain the iteration subscript and value, and the functional style (note that FP focuses on immutable data structures, forEach is inherently a side effect, so only FP Form but no God) is extremely refreshing to write. but! I wonder if any of you students have noticed: once you start forEach, you can't stop. . .

forEach accepts a callback function, you canreturnin advance, which is equivalent tocontinuein a handwritten loop. But you can'tbreak- because there is no loop in the callback function for you tobreak:

[1, 2, 3, 4, 5].forEach(x => { console.log(x); if (x === 3) { break; // SyntaxError: Illegal break statement } });
Copy after login

There are still solutions. Other functional programming languages such asscalahave encountered similar problems. They provide a function
break, which throws an exception.

We can follow this approach to achieve thebreakofarr.forEach:

try { [1, 2, 3, 4, 5].forEach(x => { console.log(x); if (x === 3) { throw 'break'; } }); } catch (e) { if (e !== 'break') throw e; // 不要勿吞异常。。。 }
Copy after login

still There are other ways, such as usingArray.prototype.someinstead ofArray.prototype.forEach.

Consider the characteristics of Array.prototype.some. Whensomefinds a value that meets the conditions (the callback function returnstrue), the loop will be terminated immediately, using this Features can simulatebreak: The return value of

[1, 2, 3, 4, 5].some(x => { console.log(x); if (x === 3) { return true; // break } // return undefined; 相当于 false });
Copy after login

someis ignored, and it has been separated from the judgment of whether there are elements in the array that meet the given conditions. original meaning.

Before ES6, I mainly used this method (in fact, due to the expansion of Babel code, I also use it occasionally now). ES6 is different. We have for...of.for...ofis a real loop and canbreak:

for (const x of [1, 2, 3, 4, 5]) { console.log(x); if (x === 3) { break; } }
Copy after login

But there is a problem,for...ofseems to take Less than the subscript of the loop. In fact, the JavaScript language developers thought of this problem and can solve it as follows:

for (const [index, value] of [1, 2, 3, 4, 5].entries()) { console.log(`arr[${index}] = ${value}`); }
Copy after login

Array.prototype.entries

##for...ofandforEachPerformance test: https://jsperf.com/array-fore...for...ofis faster in Chrome

The above is the detailed content of Difficulties in JavaScript array operations (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!