Home >Web Front-end >JS Tutorial >Detailed example of the new Array method in ECMAScript5_javascript skills
ECMAScript5 provides a series of new API interfaces. Most of these interfaces are supported in new browsers. IE9, Chrome, and FirFor all support it. There are also a few APIs that are not supported by all browsers. The following content is only Introduces most of the supported APIs. Using the new API we can design very reliable classes while maintaining the original JavaScript style.
The ECMAScript5 standard was released on December 3, 2009. It brings some new methods to improve existing Array array operations. (note compatibility)
In ES5, there are a total of 9 Array methods: http://kangax.github.io/compat-table/es5/
Array.prototype.indexOf Array.prototype.lastIndexOf Array.prototype.every Array.prototype.some Array.prototype.forEach Array.prototype.map Array.prototype.filter Array.prototype.reduce Array.prototype.reduceRight
7 of the methods are listed below. The first 5 methods are very common and used by many developers:
1. indexOf()
The indexOf() method returns the position of the first element found in the array, or -1 if it does not exist.
var arr = ['apple', 'orange', 'pear'], found = false; // 未使用 for (var i = 0, l = arr.length; i < l; i++) { if (arr[i] === 'orange') { found = true; } } console.log("found:", found); // ==> found: true // 使用后 console.log("found:", arr.indexOf("orange") != -1); // ==> found: true
2. filter()
The filter() method creates a new array matching the filter conditions.
When filter() is not used:
var arr=[{"name":"apple", "count": 2},{"name":"orange", "count": 5},{"name":"pear", "count": 3},{"name":"orange", "count": 16},] var newArr = []; for (var i = 0; i < arr.length; i++) { if (arr[i].name === "orange") { newArr.push(arr[i]); } } console.log("Filter results:", newArr);
used filter():
var newArr = arr.filter(function(item) { return item.name === "orange"; }); console.log("Filter results:", newArr);
3. forEach()
forEach executes the corresponding method for each element and is used to replace the for loop.
var arr = [1, 2, 3, 4, 5, 6, 7, 8]; // 使用for循环 for (var i = 0, l = arr.length; i < l; i++) { console.log(arr[i]); } // 使用forEach循环 arr.forEach(function(item, index) { console.log(item); });
4. map()
After map() performs certain operations (mapping) on each element of the array, it will return a new array.
var oldArr = [{first_name: "Colin",last_name: "Toh"}, {first_name: "Addy",last_name: "Osmani"}, {first_name: "Yehuda",last_name: "Katz"}]; function getNewArr() { var newArr = []; for (var i = 0; i < oldArr.length; i++) { var item = oldArr[i]; item.full_name = [item.first_name, item.last_name].join(" "); newArr[i] = item; } return newArr; } var personName = getNewArr(); personName.forEach(function(item, index) { console.log(item); }) /****输出结果: Object {first_name: "Colin", last_name: "Toh", full_name: "Colin Toh"} Object {first_name: "Addy", last_name: "Osmani", full_name: "Addy Osmani"} Object {first_name: "Yehuda", last_name: "Katz", full_name: "Yehuda Katz"} ****/
Use map() method:
function getNewArr() { return oldArr.map(function(item, index) { item.full_name = [item.first_name, item.last_name].join(" "); return item; }) } var personName = getNewArr(); personName.forEach(function(item, index) { console.log(item); }) /****输出结果: Object {first_name: "Colin", last_name: "Toh", full_name: "Colin Toh"} Object {first_name: "Addy", last_name: "Osmani", full_name: "Addy Osmani"} Object {first_name: "Yehuda", last_name: "Katz", full_name: "Yehuda Katz"} ****/
5. reduce()
reduce() can implement the function of an accumulator, reducing each value of the array (from left to right) to a value. It can also be understood as: let the previous and subsequent items in the array perform some kind of operation and accumulate the final value;
Scenario: Count how many unique words there are in an array;
var arr = ["apple", "orange", "apple", "orange", "pear", "orange"]; function getWordCnt() { var obj = {}; for (var i = 0; i < arr.length; i++) { var item = arr[i]; obj[item] = (obj[item] + 1) || 1; } return obj; } console.log(getWordCnt()); // 输出结果: // Object {apple: 2, orange: 3, pear: 1}
After using reduce():
var arr = ["apple", "orange", "apple", "orange", "pear", "orange"]; function getWordCnt() { return arr.reduce(function(prev, next) { prev[next] = (prev[next] + 1) || 1; return prev; }, {}); } console.log(getWordCnt()); // 输出结果: // Object {apple: 2, orange: 3, pear: 1}
6, array.some(callback[, thisObject]); callback: function used to test certain elements.
thisObject: The object is used as the execution callback.
Detect whether certain items in the array meet the conditions;
var scores = [45, 60, 70, 65, 95, 85]; var current = 60; function passed(score) { return score > current; } console.log(scores.some(passed)); // == > true
7. array.every(callback[, thisObject]); callback : function is used to test each element. thisObject: The object is used as the execution callback.
Check whether each item in the array meets the conditions;
var scores = [45, 60, 70, 65, 95, 85]; var current = 60; function passed(score) { return score > current; } console.log(scores.every(passed)); // == > false
The above example introduces you to the new Array method in ECMAScript5. I hope it will be helpful to you!