Home  >  Article  >  Web Front-end  >  js uses API examples that can traverse arrays to share

js uses API examples that can traverse arrays to share

小云云
小云云Original
2018-01-29 11:41:071384browse

There are many APIs in js that can traverse arrays. Since they are so well encapsulated, why not use them during normal development? This article talks about the use of APIs such as forEach, map, filter, some, every, and reduce, and they are similar to ordinary APIs. The for statement is used for comparison. This article mainly shares with you API examples of using traversable arrays in js. I hope it can help you.

We use an object array as test data:

const testArr = [
    { id: 1, name: '张三', age: 18 }, 
    { id: 2, name: '李四', age: 24 }, 
    { id: 3, name: '王小二', age: 22 }
];

forEach

Print out the IDs of all objects. The for statement is written as follows:

for (let i = 0, len = testArr.length; i < len; i++) {
    console.log(testArr[i].id); // 1, 2, 3
}

Simple and easy Got it, let’s take a look at how forEach is written:

testArr.forEach(item => console.log(item.id)); // 1, 2, 3

The results of the two are the same. The for statement is an imperative programming style, while forEach is a declarative programming style; the former will tell the machine what to do, while the latter Just focus on what to do. We recommend the latter way of writing, and should try to use forEach, so that we don't need to write a long series of expressions in for(), so why not. (ps: If you are picky about performance, just use for!)

map

Now we want to get the names of all objects and form a new array. The for statement is written as follows:

let names = [];

for (let i = 0, len = testArr.length; i < len; i++) {
    names.push(testArr[i].name);
}

console.log(names); // [ &#39;张三&#39;, &#39;李四&#39;, &#39;王小二&#39; ]

It’s quite verbose. For this problem of performing specified operations on each element of the original array and finally returning the new array, map is a perfect choice:

testArr.map(item => item.name); // [ '张三', '李四', '王小二' ]

Compared with the for statement, map is so elegant!

Regarding map, there is something to note:

[1, 2, 3].map(parseInt); // [ 1, NaN, NaN ]

Some students here may be a little confused, why is the result not [1, 2, 3]?

In fact, it is very simple. Map will pass three parameters (the element currently being traversed, the current element index, and the original array itself) to parseInt, and parseInt can have two parameters.

At this time, it is equivalent to executing the following code:

parseInt(1, 0); // 1
parseInt(2, 1); // NaN
parseInt(3, 2); // NaN

So the result is [1, NaN, NaN], not [1, 2, 3].

filter

Sometimes we need to filter out elements that meet specified conditions, such as objects whose age is greater than 18. For is written as follows:

let newArr = [];

for (let i = 0, len = testArr.length; i < len; i++) {
    if (testArr[i].age > 18) {
        newArr.push(testArr[i]);
    }
}

console.log(newArr); // [ { id: 2, name: '李四', age: 24 }, { id: 3, name: '王小二', age: 22 } ]

As you can see, the writing is very simple Long-winded, it is very convenient to use filter at this time:

testArr.filter(item => item.age > 18); // [ { id: 2, name: '李四', age: 24 }, { id: 3, name: '王小二', age: 22 } ]

filter can also be used to remove duplicates from arrays. The code is as follows:

const arr2 = [1, 2, 4, 1, 3, 2, 6];

arr2.filter((item, idx, arr) => {
    return arr.indexOf(item) === idx;
}); // [ 1, 2, 4, 3, 6 ]

map + filter

Get all objects For a certain attribute, you need to determine whether the object has this attribute in advance. For is a bit ugly to write:

function getAllOfSomeProps (array, props) {
    let arr = [];

    array.forEach((item) => {           
        if (item[props]) {
            arr.push(item[props]); // => item[props] && arr.push(item[props])
        }
    })

    return arr;
}

getAllOfSomeProps(testArr, 'sex'); // []
getAllOfSomeProps(testArr, 'id'); // [ 1, 2, 3 ]
getAllOfSomeProps(testArr, 'name'); // [ '张三', '李四', '王小二' ]

The combination of map + filter is much more elegant:

return array.map(item => item[props]).filter(item => item);

Let’s give another comparison A popular example, for example, we need to get the names of all objects in the array whose age is greater than 18. The for statement is as follows:

let newNames = [];

for (let i = 0, len = testArr.length; i < len; i++) {
    if (testArr[i].age > 18) {
        newNames.push(testArr[i].name);
    }
}

console.log(newNames); // [ '李四', '王小二' ]

Let’s look at the way of writing map + filter:

testArr.filter(item => item.age > 18).map(item => item.name); // [ '李四', '王小二' ]

is still very elegant.

some

Sometimes we need to add new objects but some attributes cannot be repeated. For is written as follows:

function isRepeat (array, props, value) {
    for (let i = 0, len = array.length; i < len; i++) {
        if (array[i][props] === value) {
            return true;
        }
    }

    return false;
}

some method tests whether certain elements in the array pass The test of the specified function is rewritten as follows:

function isRepeat (array, props, value) {
    return array.some(item => item[props] === value);
}

isRepeat(testArr, 'name', '张三'); // true
isRepeat(testArr, 'name', '李白'); // false

every

We need to detect whether each object in an array has a certain attribute. For is written as follows:

function hasSomeProps (array, props) {
    for (let i = 0, len = array.length; i < len; i++) {
        if (!array[i][props]) {
            return false;
        }
    }

    return true;
}

Every method tests whether all elements of the array pass the test of the specified function. Rewrite as follows:

function hasSomeProps (array, props) {
    return array.every(item => item[props]);
}

hasSomeProps(testArr, 'name'); // true

Break out of the loop

Sometimes it is necessary to terminate the loop when certain conditions are met, such as printing object information until the name is Li Si:

for use break:

for (let i = 0, len = testArr.length; i < len; i++) {
    if (testArr[i].name === &#39;李四&#39;) {
        break;
    }
    console.log(testArr[i]); // { id: 1, name: &#39;张三&#39;, age: 18 }
}

some, when the condition is true, return true to jump out of the loop:

testArr.some((item) => {
    if (item.name === '李四') {
        return true;
    }
    console.log(item); // { id: 1, name: '张三', age: 18 }
})

every, when the condition is true, return false to jump out of the loop:

testArr.every((item) => {
    if (item.name === '李四') {
        return false;
    }
    console.log(item); // { id: 1, name: '张三', age: 18 }
})

Because forEach has no break , here we can use some, every instead.

reduce

Calculate the sum of [343, 34, 232, 4, 343, 335, 353535], for is written as follows:

const arr = [343, 34, 232, 4, 343, 335, 353535];

let sum = 0;
for (let i = 0, len = arr.length; i < len; i++) {
    sum += arr[i];
}
console.log(sum); // 354826

Use reduce to do this The accumulation operation is very convenient:

arr.reduce((prev, curr) => prev + curr) // 354826

In fact, the usage is far more than that. Students can slowly accumulate it in their daily study or work.

Summary: You should try to use these APIs when traversing arrays. Flexible use can make the code more elegant. This style of using functions and chain calls as much as possible is very close to functional programming and can improve code quality.

Related recommendations:

Summary of JavaScript methods for traversing arrays

JQuery summary of various example codes for traversing arrays and json objects

A summary of several usages of php traversing arrays


The above is the detailed content of js uses API examples that can traverse arrays to share. For more information, please follow other related articles on the PHP Chinese website!

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