In the last few years ,javaScript The language has been updated several times . In order to keep up with the pace of technological innovation , Always keep a learning heart . Take advantage of the lunch break to learn to be familiar with the array includes、reduce Use .

Array.prototype.includes

ES7 Add support for this method ,includes() Method is used to determine whether an array contains an element with a specified value , And return the Boolean value true or false, Return if included true, Otherwise return to false.

grammar

arr.includes(valueToFind[, fromIndex])

Parameters

  • valueToFind( must ): The value of the element to look for , Comparing strings and characters is case sensitive .
  • fromIndex( Optional ): From an array fromIndex Start searching at index valueToFind.
    • negative , Then in ascending order from array.length + fromIndex The index begins to search ( Even if you jump forward from the end fromIndex The absolute value of an index , Then search back ).
    • The default value is 0.

Return value

Include returns true, Otherwise return to false.

example

// ES5 Code
const numbers = [" One ", " Two ", " 3、 ... and ", " Four "];
console.log(numbers.indexOf(" One ") > -1); // true
console.log(numbers.indexOf(" 6、 ... and ") > -1); // false
// ES7 Code
console.log(numbers.includes(" One ")); // true
console.log(numbers.includes(" 6、 ... and ")); // false
console.log(numbers.includes(" One ",1)); // false, Index from array to `1` Look back
console.log(numbers.includes(" One ", -3)); // true, from  `array.length + fromIndex`  After the index of , From the index above to 1 Start equivalence 

Use includes Methods make the code short and easy to understand .include Method is also convenient when comparing values , The following code .

//  In the past
const day = " Tuesday ";
if (day === " Tuesday " || day === " Wednesday " || day === " Thursday ") {
    console.log(day);
}
//  Now?
if ([" Tuesday ", " Wednesday ", " Thursday "].includes(day)) {
    console.log(day);
}

Array.prototype.reduce

reduce() Method for each element in the array reducer function ( Ascending execution ), Summarize its results into a single return value .

grammar

Array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

Execute... For each element in the array in turn callback function , Does not include elements in the array that have been deleted or have never been assigned .

Parameters

  • callback( must ): Execute each value in the array ( If not provided initialValue Except for the first value ) Of reducer function , There are four parameters

    • accumulator( must ): The accumulator accumulates the return value of the callback ; It is the cumulative value returned when the callback was last called , The initial value can be determined by initialValue Definition , The default value is the first element value of the array , The accumulator will hold the value of the last operation , Just like static variables

    • currentValue( must ): The element being processed in the array

    • index( Optional ): The index of the current element being processed in the array . If provided initialValue, The starting index number is 0, Otherwise from index 1 start .

      Be careful : If not provided initialValue,reduce From the index 1 Where we started callback Method , Skip the first index . Provided initialValue, From the index 0 Start .

    • array( Optional ): call reduce() Array of

  • initialValue( Optional ): As the first call callback The value of the first parameter of the function . If no initial value is provided , Then the first element in the array... Will be used . Called on an empty array without an initial value reduce Will be an error .

Return value

Function to accumulate the result of processing .

example

const arrNumbers = [1, 2, 3, 4, 5];
const reduceNumbers = (arrayNumbers, accumulatorInitVal = false) => {
    const reduceCallback = (accumulator, currentVal, currentIndex) => {
        console.log(` Current index :${currentIndex}`);
        return accumulator + currentVal;
    };
    return accumulatorInitVal
        ? arrayNumbers.reduce(reduceCallback, accumulatorInitVal)
        : arrayNumbers.reduce(reduceCallback);
};
console.log(reduceNumbers(arrNumbers)); // 15, The initial value of the accumulator is the value of the first element of the array 1
console.log(reduceNumbers(arrNumbers, 10)); // 25, The initial value of the accumulator is 10

console.log( Current index :${currentIndex}), In order to see the index value more intuitively .

The first undefined initial value output is as follows :

 Current index :1
Current index :2
Current index :3
Current index :4

The second definition of the accumulator initial value output is as follows :

 Current index :0
Current index :1
Current index :2
Current index :3
Current index :4

Now let's look at a wonderful demand , For some reason , You need a new array containing the full names of all users ( Their last names , Add their names ), But only if they are 20 How old , And their full name is 3 It's only when I'm a word . Don't ask why we need such a wonderful subset of data , The product manager asked , We are happy to help ^_^

const users = [
    {
        firstName: " Firm ",
        lastName: " Grandchildren ",
        age: 37,
    },
    {
        firstName: " Strategy ",
        lastName: " Grandchildren ",
        age: 21,
    },
    {
        firstName: " Ge Liang ",
        lastName: " various ",
        age: 28,
    },
    {
        firstName: " To prepare ",
        lastName: " Liu ",
        age: 44,
    },
    {
        firstName: " system ",
        lastName: " Pang ",
        age: 22,
    },
    {
        firstName: " dimension ",
        lastName: " ginger ",
        age: 19,
    },
    {
        firstName: " Bowen ",
        lastName: " Liu ",
        age: 22,
    },
];
const getFullName = (user) => `${user.lastName}${user.firstName}`;
const filterByAge = (user) => user.age >= 20 && user.age < 30;
//  Regular implementation
const getFilterResult = users
    //   The first step is to screen for age 20-30 Between users
    .filter((user) => filterByAge(user))
    //   Splicing full name
    .map((user) => getFullName(user))
    //   Screening
    .filter((fullName) => fullName.length === 3);
console.log(getFilterResult);   // [ ' Zhugeliang ', ' Liu Bowen ' ]
//  Iteratively
const iterationsFilterResult = (arrayResult, currentUser) => {
    const fullname = getFullName(currentUser);
    if (filterByAge(currentUser) && fullname.length === 3) {
        arrayResult.push(fullname);
    }
    return arrayResult;
};
console.log(users.reduce(iterationsFilterResult, []));  // [ ' Zhugeliang ', ' Liu Bowen ' ]