Home > Web Front-end > JS Tutorial > Difficulties in JavaScript array operations (detailed tutorial)

Difficulties in JavaScript array operations (detailed tutorial)

亚连
Release: 2018-06-20 13:56:30
Original
2195 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 to enumerable: 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 to null

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.stringify and JSON.parse operate 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.find is a new array search function in ES2015, which is similar to Array.prototype.some, but cannot replace the latter.

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

arr.find is to find the value in the array and then further process it. It is generally used in the case of object array; arr.some is 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 between Array.prototype.map and ## The actual meaning of #Array.prototype.forEach.

map is called MAP in 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).

forEach There are not so many explanations. It simply processes all items in the array with a certain function. Since forEach has no return value (returns undefined), its callback function usually contains side effects, otherwise this forEach is meaningless.

It is true that

map is more powerful than forEach, but map will create a new array and occupy memory. If you don't use the return value of map, then you should use forEach

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 can return in advance, which is equivalent to continue in a handwritten loop. But you can't break - because there is no loop in the callback function for you to break:

[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 as scala have encountered similar problems. They provide a function
break, which throws an exception.

We can follow this approach to achieve the break of arr.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 using Array.prototype.some instead of Array.prototype.forEach.

Consider the characteristics of Array.prototype.some. When some finds a value that meets the conditions (the callback function returns true), the loop will be terminated immediately, using this Features can simulate break: 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

some is 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...of is a real loop and can break:

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...of seems 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...of and forEach Performance test: https://jsperf.com/array-fore... for...of is 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template