Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of es6 loop operation

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

What are the knowledge points of this article "what are the methods of es6 cycle operation?" most people do not understand, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what are the methods of es6 loop operation" article.

First, make good use of filter,map and other high-order traversal functions added by ES6.

Problem 1: remove null values from the array

Const arr = [3,4,5,2,3, undefined, null, 0, "]

Problem 2: add the VIP user balance in the array by 10

Const users = [

{username: "Kelly", isVIP: true, balance: 20}

{username: "Tom", isVIP: false, balance: 19}

{username: "Stephanie", isVIP: true, balance: 30}

]

Add: some people say that it is obvious that forEach should be used here, you give an example for example! I'm speechless. ForEach is used to perform side effects, okay? You changed the original data. My habit is to use Immutable data. If you want to change the data, just be happy.

Question 3: determine whether the string contains vowels

Const randomStr = "hdjrwqpi"

Question 4: determine whether all users are adults

Const users = [

{name: "Jim", age: 23}

{name: "Lily", age: 17}

{name: "Will", age: 25}

]

Question 5: find the first minor among the above users

Const findTeen = users = > users.find (user = > user.age

< 18); findTeen(users); 问题六:将数组中重复项清除 const dupArr = [1, 2, 3, 3, 3, 3, 6, 7]; 问题七:生成由随机整数组成的数组,数组长度和元素大小可自定义 const genNumArr = (length, limit) =>

Array.from ({length}, _ = > Math.floor (Math.random () * limit))

GenNumArr (10,100)

Second, understand and skillfully use reduce

Problem 8: define reduce without the help of native higher-order functions

Answer:

Const reduce = (f, acc, arr) = > {

If (arr.length = 0) return acc

Const [head,... tail] = arr

Return reduce (f, f (head, acc), tail)

}

Problem 9: converting a multi-layer array to a single-layer array

Const nestedArr = [1,2, [3,4, [5,6]

Answer:

Const flatten = arr = >

Arr.reduce (

(flat, next) = > flat.concat (Array.isArray (next)? Flatten (next): next)

[]

);

Question 10: convert the following array into objects, and key/value corresponds to the two values of the inner array.

Const objLikeArr = [["name", "Jim"], ["age", 18], ["single", true]]

Answer:

Const fromPairs = pairs = >

Pairs.reduce ((res, pair) = > ((res [pair [0]] = pair [1]), res), {})

FromPairs (objLikeArr)

Question 11: take out the deep attributes in the object

Const deepAttr = {a: {b: {c: 15}

Question 12: put the men and women in the users into different arrays:

Const users = [

{name: "Adam", age: 30, sex: "male"}

{name: "Helen", age: 27, sex: "female"}

{name: "Amy", age: 25, sex: "female"}

{name: "Anthony", age: 23, sex: "male"}

]

Answer:

Const partition = (arr, isValid) = >

Arr.reduce (

([pass, fail], elem) = >

IsValid (elem)? [[... pass, elem], fail]: [pass, [... fail, elem]]

[[], []]

);

Const isMale = person > person.sex = = "male"

Const [maleUser, femaleUser] = partition (users, isMale)

Question 13: the calculation process of reduce is called catamorphism in category theory, that is, a deformation of connections. The opposite deformation is called anamorphism. Now let's define a function unfold, which is opposite to the calculation process of reduce (Note: reduce is called fold in Haskell, corresponding to unfold).

Const unfold = (f, seed) = > {

Const go = (f, seed, acc) = > {

Const res = f (seed)

Return res? Go (f, res [1], acc.concat (res [0])): acc

}

Return go (f, seed, [])

}

According to this unfold function, define a range function in Python.

Answer:

Const range = (min, max, step = 1) = >

Unfold (x = > x)

< max && [x, x + step], min); 三,用递归代替循环(可以break!) 问题十四: 将两个数组每个元素一一对应相加。注意,第二个数组比第一个多出两个,不要把第二个数组遍历完。 const num1 = [3, 4, 5, 6, 7]; const num2 = [43, 23, 5, 67, 87, 3, 6]; const zipWith = f =>

Xs = > ys = > {

If (xs.length = 0 | | ys.length = 0) return []

Const [xHead,... xTail] = xs

Const [yHead,... yTail] = ys

Return [f (xHead) (yHead),... zipWith (f) (xTail) (yTail)]

}

Const add = x = > y = > x + y

ZipWith (add) (num1) (num2)

Question 15: extract members of the Stark family. Note that the target data is in front of the array, and it is wasteful to use the filter method to traverse the entire array.

Const houses = [

"Eddard Stark"

"Catelyn Stark"

"Rickard Stark"

"Brandon Stark"

"Rob Stark"

"Sansa Stark"

"Arya Stark"

"Bran Stark"

"Rickon Stark"

"Lyanna Stark"

"Tywin Lannister"

"Cersei Lannister"

"Jaime Lannister"

"Tyrion Lannister"

"Joffrey Baratheon"

]

Answer:

Const takeWhile = f = > ([head,... tail]) = >

F (head)? [head,... takeWhile (f) (tail)]: []

Const isStark = name = > name.toLowerCase () .includes ("stark")

TakeWhile (isStark) (houses)

Question 16: find the odd numbers in the array, and then take out the first four:

Const numList = [1,3,11,4,2,5,6,7]

Answer:

Const takeFirst = (limit, f, arr) = > {

If (limit = 0 | | arr.length = 0) return []

Const [head,... tail] = arr

Return f (head)

? [head,... takeFirst (limit-1, f, tail)]

: takeFirst (limit, f, tail)

}

Const isOdd = n = > n% 2 = = 1

TakeFirst (4, isOdd, numList)

Fourth, the pitfalls that may be encountered when traversing an array using higher-order functions

Question 17: take even numbers from an array of random integers of length 1 million and multiply all numbers by 3

/ / use the auxiliary function we just defined to generate an array that meets the requirements.

Const bigArr = genNumArr (1e6, 100)

The answer that works:

Const isEven = num = > num 2 = = 0

Const triple = num = > num * 3

BigArr.filter (isEven) .map (triple)

Note that the above solution traverses the array twice, which is undoubtedly a waste. If you write a for loop, you only need to iterate through it once:

Const results = []

For (let I = 0; I

< bigArr.length; i++) { if (isEven(bigArr[i])) { results.push(triple(bigArr[i])); } } 在我的电脑上测试,先 filter 再 map 的方法耗时 105.024 ms,而采用 for 循环的方法耗时仅 25.598 ms!那是否说明遇到此类情况必须用 for 循环解决呢? No! 五,死磕到底,Transduce! 我们先用 reduce 来定义 filter 和 map,至于为什么这样做等下再解释。 const filter = (f, arr) =>

Arr.reduce (acc, val) = > (f (val) & & acc.push (val), acc), [])

Const map = (f, arr) = > arr.reduce ((acc, val) = > (acc.push (f (val)), acc), [])

The redefined filter and map share common logic. We call this part of the common logic reducer. With the common logic in place, we can further abstract, extract the reducer, and pass in filter and map:

Const filter = f = > reducer = > (acc, value) = > {

If (f (value)) return reducer (acc, value)

Return acc

}

Const map = f = > reducer = > (acc, value) = > reducer (acc, f (value))

Now that filter is the same as map's function signature, we can function composition the function.

Const pushReducer = (acc, value) = > acc.push (value), acc)

BigNum.reduce (map (triple) (filter (isEven) (pushReducer)), [])

But this kind of nesting writing is too easy to read and easy to make mistakes. We can write a tool function to assist the function combination:

Const pipe = (... fns) = > (... args) = > fns.reduce ((fx, fy) = > fy (fx),... args)

Then we can combine functions gracefully:

BigNum.reduce (

Pipe (

Filter (isEven)

Map (triple)

) (pushReducer)

[]

);

After testing (using console.time () / console.timeEnd ()), the above writing takes 33.898 ms, which is only 8 ms slower than the for loop. I think this small performance sacrifice is acceptable for the sake of the maintainability and readability of the code.

This way of writing is called transduce. There are many tool libraries that provide transducer functions. Like transducers-js. In addition to traversing arrays with transducer, you can also use it to traverse objects and other datasets. It's quite powerful.

Six, for cycle and for. The difference of of cycle

For... The of loop is generated in order to traverse the Iterable data type after ES6 introduced Iterator. The Iterable data types of EcmaScript are arrays, strings, Set and Map. For... The of loop is a heavy operation (I don't know the details). If you use AirBNB's ESLint rules, use for in your code. It is forbidden for of to traverse arrays.

So, for... In which scenarios should the of loop be used? The fair use scenario I've found so far is to traverse a custom Iterable. Let's take a look at this topic:

Problem 18: traverse the names of members of the Stark family, pause for one second each time, then print the name of the current traversal, go back to the first element and start over again, an infinite loop.

Const starks = [

"Eddard Stark"

"Catelyn Stark"

"Rickard Stark"

"Brandon Stark"

"Rob Stark"

"Sansa Stark"

"Arya Stark"

"Bran Stark"

"Rickon Stark"

"Lyanna Stark"

]

Answer:

Function* repeatedArr (arr) {

Let I = 0

While (true) {

Yield arr [iTunes +% arr.length]

}

}

Const infiniteNameList = repeatedArr (starks)

Const wait = ms = >

New Promise (resolve = > {

SetTimeout () = > {

Resolve ()

}, ms)

});

(async () = > {

For (const name of infiniteNameList) {

Await wait (1000)

Console.log (name)

}

) ()

Seventh, give up stubbornness, you really need to use for cycle

The problems mentioned above basically cover most of the scenarios where you need to use for loops. Can we guarantee that we will never use for loops? Actually, no. What I've said so much is to encourage people not to write for loops, not to use for loops. The higher-order functions such as map,filter on the array prototype chain are actually implemented by the for loop at the bottom. When you need to write some underlying code, you still need to write a for loop. Take a look at this example:

Number.prototype [Symbol.iterator] = function* () {

For (let I = 0; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report