PrefaceThe JavaScript language has undergone several updates over the past few years. In order to keep up with the pace of technological updates, always keep a learning attitude. Take advantage of the break time to learn and familiarize yourself with the use of array includes and reduce. Array.prototype.includesES7 adds support for this method. The includes() method is used to determine whether an array contains an element with a specified value and returns a Boolean value of true or false. If it is included, it returns true, otherwise it returns false. grammar
parameter
Return ValueReturns true if contained, false otherwise. Examples// ES5 Code const numbers = ["one", "two", "three", "four"]; console.log(numbers.indexOf("一") > -1); // true console.log(numbers.indexOf("六") > -1); // false // ES7 Code console.log(numbers.includes("一")); // true console.log(numbers.includes("六")); // false console.log(numbers.includes("一",1)); // false, search from array index 1 backwardsconsole.log(numbers.includes("一", -3)); // true, search from array.length + fromIndex backwards, equivalent to starting from index 1 above Using the includes method can make the code short and easy to understand. The include method is also convenient for comparing values, as shown in the following code. // past const day = "Tuesday"; if (day === "Tuesday" || day === "Wednesday" || day === "Thursday") { console.log(day); } // Nowif (["Tuesday", "Wednesday", "Thursday"].includes(day)) { console.log(day); } Array.prototype.reduceThe reduce() method executes the reducer function on each element in the array (in ascending order), summarizing the results into a single return value. grammar
Executes the callback function for each element in the array in turn, excluding elements in the array that have been deleted or have never been assigned a value. parameter
Return ValueThe function accumulates the results of processing. Examples 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}) is to see the index value more intuitively. The first time the initial value is not defined, the output is as follows:
The second definition of the accumulator initial value output is as follows:
Next we have a weird requirement where, for some reason, we need a new array containing all of our users' full names (their last name, plus their first name), but only if they are in their 20s and their full name is 3 characters. Don’t ask us why we need such a weird data subset. The product manager asked and we are happy to help^_^ const users = [ { firstName: "Jian", lastName: "Sun", age: 37, }, { firstName: "策", lastName: "Sun", age: 21, }, { firstName: "Ge Liang", lastName: "朱", age: 28, }, { firstName: "備", lastName: "Liu", age: 44, }, { firstName: "统", lastName: "Pang", age: 22, }, { firstName: "维", lastName: "姜", age: 19, }, { firstName: "博文", lastName: "Liu", age: 22, }, ]; const getFullName = (user) => `${user.lastName}${user.firstName}`; const filterByAge = (user) => user.age >= 20 && user.age < 30; // Conventional implementation const getFilterResult = users // The first step is to filter users between the ages of 20 and 30.filter((user) => filterByAge(user)) // Concatenate full names.map((user) => getFullName(user)) // Filter.filter((fullName) => fullName.length === 3); console.log(getFilterResult); // ['Zhuge Liang', 'Liu Bowen'] // Iteration implementation const iterationsFilterResult = (arrayResult, currentUser) => { const fullname = getFullName(currentUser); if (filterByAge(currentUser) && fullname.length === 3) { arrayResult.push(fullname); } return arrayResult; }; console.log(users.reduce(iterationsFilterResult, [])); // [ 'Zhuge Liang', 'Liu Bowen' ] SummarizeThis is the end of this article about the basic use of javascript array includes and reduce. For more related javascript array includes and reduce content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Solve the problem of PhPStudy MySQL startup failure under Windows system
Recently, I found that the company's server t...
1. Under 800*600, if the width of the web page is...
Preface: The previous article described several c...
I logged into the backend to check the solution t...
When I surf the Net, I often see web sites filled...
A certain distance can be set between cells in a ...
CSS3 implements 2D plane transformation and visua...
Project scenario: 1. Upload file restrictions Fun...
This article shares the specific code for JavaScr...
As shown below: XML/HTML CodeCopy content to clip...
Implementation effect: 1. count(1) and count(*) W...
Recently, I was adding a series of statistical fu...
Scenario Description In a certain system, the fun...
Copy code The code is as follows: <div content...
Table of contents 1 Review 2 Five strategies for ...