Home > Web Front-end > JS Tutorial > Basics of array operations in JavaScript

Basics of array operations in JavaScript

小云云
Release: 2017-12-18 16:10:00
Original
1349 people have browsed it

This article mainly shares with you the basics of array operations in JavaScript. Do not 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 an array:

  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.

  1. # will traverse the values ​​on the object prototype chain.

If you change the prototype object of the array (such as a polyfill) without setting it to <span style="font-size: 14px;">enumerable: false</span>, for_in will traverse these things.

  1. The operation efficiency is low.

#Although theoretically JavaScript uses the form of objects to store arrays, the JavaScript engine will be 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 be looking for for_of

##Don’t use JSON.parse(JSON.stringify()) deep copy array

Someone uses JSON Medium-deep copy of an object or array. Although this is a simple and convenient method in most cases, it may also cause unknown bugs because:

  1. will convert some specific values ​​into null<span style="font-size: 14px;"></span>

NaN, undefined, Infinity For these values ​​that are not supported in JSON, they will be converted to null. After deserialization, it will naturally be null<span style="font-size: 14px;"></span>

  1. , and key-value pairs with undefined values ​​will be lost

Keys with undefined values ​​will be ignored during JSON serialization, and will be lost after deserialization.

  1. The Date object will be Convert to string

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

  1. which is inefficient.

As native functions, JSON.stringify<span style="font-size: 14px;"></span> and <span style="font-size: 14px;"></span> JSON.parse<span style="font-size: 14px;"></span> The speed of operating JSON strings by itself is very fast. 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 TypedArray, Copying RegExp objects

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

Do not use arr.find instead of arr .some

##Array.prototype.find<span style="font-size: 14px;"></span> is a new array search function in ES2015, which is the same as Array.prototype.some<span style="font-size: 14px;"></span> has similarities, but is not a replacement for the latter.

Array.prototype.find<span style="font-size: 14px;"></span> Returns the first value that meets the conditions and directly uses this value to do if<span style="font-size: 14px;"></span> Determine whether it exists. What if the qualified value happens to be 0?

arr.find<span style="font-size: 14px;"></span> 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<span style="font-size: 14px;"></span> is used to check 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 ## The actual meaning of #Array.prototype.map<span style="font-size: 14px;"></span> and Array.prototype.forEach<span style="font-size: 14px;"></span>.

##map<span style="font-size: 14px;"></span> Chinese is called MAP<span style="font-size: 14px;"></span>, which is done by A sequence executes a function in sequence to derive another new sequence. This function usually has no side effects and does not modify the original array (so-called pure function).

forEach<span style="font-size: 14px;"></span> There are not so many explanations. It simply processes all the items in the array with a certain function. Since forEach<span style="font-size: 14px;"></span> has no return value (returns undefined), its callback function usually contains side effects, otherwise this <span style="font-size: 14px;"></span> forEach<span style="font-size: 14px;"></span> is meaningless.

Indeed

map<span style="font-size: 14px;"></span> is better than forEach<span style="font-size: 14px;"></span> More powerful, but map<span style="font-size: 14px;"></span> will create a new array and occupy memory. If you don't use the return value of map<span style="font-size: 14px;"></span>, then you should use forEach<span style="font-size: 14px;"></span>

Supplement: forEach and break

Before ES6, there were two main methods for traversing arrays: handwritten loops using subscripts to iterate, and using

Array.prototype.forEach<span style="font-size: 14px;"></span>. 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 subscript and value of the iteration, and the functional style (note that FP focuses on immutable data structures, and forEach is inherently a side effect exists, so there is only the form of FP but no God) It is very 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<span style="font-size: 14px;"></span> in advance, which is equivalent to in a handwritten loop continue<span style="font-size: 14px;"></span>. But you can't #break<span style="font-size: 14px;"></span> - because there is no loop in the callback function for you to break<span style="font-size: 14px;"></span>:

<span style="font-size: 14px;">[1, 2, 3, 4, 5].forEach(x => {<br>  console.log(x);<br>  if (x === 3) {<br>    break;  // SyntaxError: Illegal break statement<br>  }<br>});<br></span>
Copy after login

There are still solutions. Other functional programming languages ​​such as

scala<span style="font-size: 14px;"></span> have encountered similar problems. It provides a function break, which is used to throw An exception occurs.

Basics of array operations in JavaScript##We can follow this approach to achieve

arr.forEach<span style="font-size: 14px;">'s</span><span style="font-size: 14px;">break</span><span style="font-size: 14px;">:</span>

<span style="font-size: 14px;">try {<br>  [1, 2, 3, 4, 5].forEach(x => {<br>    console.log(x);<br>    if (x === 3) {<br>      throw 'break';<br>    }<br>  });<br>} catch (e) {<br>  if (e !== 'break') throw e; // 不要勿吞异常。。。<br>}<br></span>
Copy after login
Disgusting B, right? There are other ways, such as using

Array.prototype.some<span style="font-size: 14px;"> instead of </span>Array.prototype.forEach<span style="font-size: 14px;">. </span>Consider the characteristics of Array.prototype.some, when

<span style="font-size: 14px;">some</span><span style="font-size: 14px;"> finds a qualified value (callback function When returning </span>true<span style="font-size: 14px;">), the loop will </span>immediately be terminated. This feature can be used to simulate break<span style="font-size: 14px;">:</span>

<span style="font-size: 14px;">[1, 2, 3, 4, 5].some(x => {<br>  console.log(x);<br>  if (x === 3) {<br>    return true; // break<br>  }<br>  // return undefined; 相当于 false<br>});<br></span>
Copy after login

<span style="font-size: 14px;">some</span> 的返回值被忽略掉了,它已经脱离了判断数组中是否有元素符合给出的条件这一原始的含义。

在 ES6 前,笔者主要使用该法(其实因为 Babel 代码膨胀的缘故,现在也偶尔使用),ES6 不一样了,我们有了 for...of。<span style="font-size: 14px;">for...of</span> 是真正的循环,可以 <span style="font-size: 14px;">break</span><span style="font-size: 14px;">:</span>

<span style="font-size: 14px;">for (const x of [1, 2, 3, 4, 5]) {<br>  console.log(x);<br>  if (x === 3) {<br>    break;<br>  }<br>}<br></span>
Copy after login

但是有个问题,<span style="font-size: 14px;">for...of</span> 似乎拿不到循环的下标。其实 JavaScript 语言制定者想到了这个问题,可以如下解决:

<span style="font-size: 14px;">for (const [index, value] of [1, 2, 3, 4, 5].entries()) {<br>  console.log(`arr[${index}] = ${value}`);<br>}<br></span>
Copy after login

Array.prototype.entries

<span style="font-size: 14px;">for...of</span><span style="font-size: 14px;">forEach</span> 的性能测试:https://jsperf.com/array-fore... Chrome 中 <span style="font-size: 14px;">for...of</span> 要快一些哦

The above is the detailed content of Basics of array operations in JavaScript. 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