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

Difficulties in JavaScript array operations (detailed tutorial)

Jun 20, 2018 pm 01:56 PM
javascript array

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

6

[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:

1

2

3

4

5

6

7

8

9

10

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

6

7

[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:

1

2

3

4

5

6

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:

1

2

3

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

PHP array merging and deduplication algorithm: parallel solution PHP array merging and deduplication algorithm: parallel solution Apr 18, 2024 pm 02:30 PM

The PHP array merging and deduplication algorithm provides a parallel solution, dividing the original array into small blocks for parallel processing, and the main process merges the results of the blocks to deduplicate. Algorithmic steps: Split the original array into equally allocated small blocks. Process each block for deduplication in parallel. Merge block results and deduplicate again.

See all articles