Some of the most common methods of operation and js array example

1. Introduction

Operating array can be described as the most basic front-end work, whether it is taken from the interface data, or filter the data, or the Add button operation rights, etc., are not open around the array of things. Many array operations, very easy to confuse beginners, is not very skilled at the wrong situation easily, so I gather information everywhere, ready to organize one, but also as to their knowledge comb.


2. Prepare

First, prepare a simple html page, with a array, in order to facilitate the presentation on this play.

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="container">
        <button @click=init>Click</button>
    </div>
</body>
<script>
    new Vue({
        el: '#container',
        methods: {
            init () {
                const array = [
                {   name: 'aa', age: 12   },
                {   name: 'bb', age: 14   },
                {   name: 'cc', age: 16   },
                {   name: 'cc', age: 16   },
            ]
        }
    })
</script>
</html>

3. Get start

2.1 filter

filter filters, you can return a new array qualified

filter has three parameters (item, index, self) represent item: an array of elements that traverse, index: the index value, self: himself.

filter simplest application, only item can be selected eligible

The following code execution

const filter = array.filter( item => item.age > 13)

console.log (filter), you can return the following results

(3) [{…}, {…}, {…}]
    0: {name: "bb", age: 14}
    1: {name: "cc", age: 16}
    2: {name: "cc", age: 16}
length: 3

filter always returns an array, if you do not meet the conditions of screening, it returns an empty array.

The item, index, self spend the same time, we can skillfully implement deduplication array of functions.

const simpleArray = ['a','a','b','c','b','a']

const simpleFilter = simpleArray.filter((item, index, self) => self.indexOf(item) === index)

console.log(simpleFilter)   

//结果

(3) ["a", "b", "c"]           

the indexOf () This has two parameters (item, offset) The first argument is the element, the second is the index of the starting position from the beginning, and where the return value is the index, lastIndexOf () just the opposite from the last a forward start. When used herein to weight, filter returns a second index element of the same, the order of the case.

2.2 sort

sort () method is very simple, you can sort the array elements

The original use that array as an example, to two arguments item1, item2

const sortArray = array.sort((item1,item2) => item1.age - item2.age)

The results can be seen, the elements in ascending order of age

(5) [{…}, {…}, {…}, {…}, {…}]
    0: {name: "dd", age: 10}
    1: {name: "aa", age: 12}
    2: {name: "bb", age: 14}
    3: {name: "cc", age: 16}
    4: {name: "cc", age: 16}
length: 5

2.3 map

map () is a new method for ES6, can not change a return after treatment on the basis of the original array to a new array, say I want all ages are +5

const mapArray = array.map( item => {
                return {
                    name: item.name,
                    age: item.age + 5
                }
            })

result:

(5) [{…}, {…}, {…}, {…}, {…}]
0: {name: "aa", age: 17}
1: {name: "bb", age: 19}
2: {name: "cc", age: 21}
3: {name: "cc", age: 21}
4: {name: "dd", age: 15}
length: 5

map There are three parameters, and filter the same, but mainly used item, index.

2.4 forEach

Array traversal recommended forEach, although theoretically use for temporary storage of array.length, reverse for higher efficiency, but so elegant wording but also what bike.

array.forEach((item,index,self) => {})

2.5 find

find () and filter () the same, except that it is used to find a specific value in the array. For example, I would like to find the name value of cc.

const findArr = array.find( item => item.name === 'cc')

The results are:

{name: "cc", age: 16}

Note that, find () will start looking for from the beginning of the index, returns true when they are found qualified elements, so if there are many name for the value cc, such as now, it will only return the first, if needed find that a precise, you need to add more conditions.

2.6 some & every & includes

The two I will not work with, but they are very special, the return value is true, false.
some () as long as there is a qualified array of species, it will return true, but every () must comply with all the conditions to return true only, otherwise false.
Includes () based on the array contains the elements, there is true.

2.7 reduce

reduce () very special, its structure consists of a method and a parameter composition (func, initv), the method takes four parameters (Total, Item, index, Self),
initv is given an initial value of the function, total is the last calculated the result, item is the element itself.

Here, we try to sum all ages again +5

const findArr = array.reduce((total,item) => total + item.age, 5)

// 结果为75

Can be seen, the initial value 5, each cycle is equal to the total time plus the total of Age, and finally return to total, to obtain the results.

2.8 splice

splice () is very simple, there are two parameters (index, num, ....), the first parameter predetermined start position, the second number is omitted, the rear element is added. You can easily add or delete operation to the original array by this method. While its return value is deleted element.

const simpleArray = ['a','a','b','c','b','a']
const spliceArr = simpleArray.splice(1, 2,'b','v')

console.log(simpleArray)  //经过更改的原数组 ["a", "b", "v", "c", "b", "a"]
console.log(spliceArr)  //移除的部分元素 ["a", "b"]

Guess you like

Origin www.cnblogs.com/lizziuno/p/11990546.html