合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
[TOC] # Array.prototype.indexOf(searchElement[, fromIndex = 0]) 返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。 * searchElement:要查找的元素 * fromIndex:开始查找的位置。 ``` var array = [2, 5, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0 ``` <br> <br> # Array.prototype.isArray(obj) 确定传递的值是否是一个 Array。 ``` // 下面的函数调用都返回 true Array.isArray([]); Array.isArray([1]); Array.isArray(new Array()); // 鲜为人知的事实:其实 Array.prototype 也是一个数组。 Array.isArray(Array.prototype); ``` <br> 当检测Array实例时, Array.isArray 优于 instanceof,因为Array.isArray能检测iframes ``` var iframe = document.createElement('iframe'); document.body.appendChild(iframe); xArray = window.frames[window.frames.length-1].Array; var arr = new xArray(1,2,3); // [1,2,3] // Correctly checking for Array Array.isArray(arr); // true // Considered harmful, because doesn't work though iframes arr instanceof Array; // false ``` <br> <br> # Array.prototype.lastIndexOf(searchElement[, fromIndex = arr.length - 1]) 返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。 <br> <br> # Array.prototype.every(callback[, thisArg]) 测试数组的所有元素是否都通过了指定函数的测试 <br> every 方法为数组中的每个元素执行一次 callback 函数,直到它找到一个使 callback 返回 false(表示可转换为布尔值 false 的值)的元素。如果发现了一个这样的元素,every 方法将会立即返回 false。否则,callback 为每一个元素返回 true,every 就会返回 true。 参数 * callback:用来测试每个元素的函数。 * thisArg:执行 callback 时使用的 this 值。 ``` function isBigEnough(element, index, array) { return (element >= 10); } var passed = [12, 5, 8, 130, 44].every(isBigEnough); // passed is false passed = [12, 54, 18, 130, 44].every(isBigEnough); // passed is true ``` <br> <br> # Array.prototype.some(callback[, thisArg]) 测试是否至少有一个元素通过由提供的函数实现的测试。 <br> `some()` 为数组中的每一个元素执行一次 `callback` 函数,直到找到一个使得 `callback` 返回一个“真值”(即可转换为布尔值 true 的值)。如果找到了这样一个值,`some()` 将会立即返回 `true`。否则,`some()` 返回 `false`。callback 只会在那些”有值“的索引上被调用,不会在那些被删除或从来未被赋值的索引上调用。 <br> 参数 * callback:用来测试每个元素的函数。 * thisArg:执行 callback 时使用的 this 值。 ``` function isBiggerThan10(element, index, array) { return element > 10; } [2, 5, 8, 1, 4].some(isBiggerThan10); // false [12, 5, 8, 1, 4].some(isBiggerThan10); // true ``` <br> <br> # Array.prototype.forEach(callback[, thisArg]) 对数组的每个元素执行一次提供的函数。 <br> `forEach` 遍历的范围在第一次调用 `callback` 前就会确定。调用 `forEach` 后添加到数组中的项不会被 `callback` 访问到。如果已经存在的值被改变,则传递给 `callback` 的值是 `forEach` 遍历到他们那一刻的值。已删除的项不会被遍历到。 <br> 没有办法中止或者跳出 forEach() 循环,除了抛出一个异常。如果你需要这样,使用 forEach() 方法是错误的。 <br> 若你需要提前终止循环,你可以使用: * 简单循环 * for...of 循环 * Array.prototype.every() * Array.prototype.some() * Array.prototype.find() * Array.prototype.findIndex() ``` var array1 = ['a', 'b', 'c']; array1.forEach(function(element) { console.log(element); }); // expected output: "a" // expected output: "b" // expected output: "c" ``` <br> <br> # Array.prototype.map(callback[, thisArg]) 创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。 ``` var array1 = [1, 4, 9, 16]; // pass a function to map const map1 = array1.map(x => x * 2); console.log(map1); // expected output: Array [2, 8, 18, 32] ``` <br> ``` // 下面的语句返回什么呢: ["1", "2", "3"].map(parseInt); // 你可能觉的会是[1, 2, 3] // 但实际的结果是 [1, NaN, NaN] // 通常使用parseInt时,只需要传递一个参数. // 但实际上,parseInt可以有两个参数.第二个参数是进制数. // 可以通过语句"alert(parseInt.length)===2"来验证. // map方法在调用callback函数时,会给它传递三个参数:当前正在遍历的元素, 元素索引, 原数组本身. // 第三个参数parseInt会忽视, 但第二个参数不会,也就是说, // parseInt把传过来的索引值当成进制数来使用.从而返回了NaN. ``` <br> ``` function returnInt(element) { return parseInt(element, 10); } ['1', '2', '3'].map(returnInt); // [1, 2, 3] // 意料之中的结果 // 也可以使用简单的箭头函数,结果同上 ['1', '2', '3'].map( str => parseInt(str) ); // 一个更简单的方式: ['1', '2', '3'].map(Number); // [1, 2, 3] // 与`parseInt` 不同,下面的结果会返回浮点数或指数: ['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300] ``` <br> <br> # Array.prototype.filter(callback[, thisArg]) 创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。 <br> `filter` 为数组中的每个元素调用一次 `callback` 函数,并利用所有使得 `callback` 返回 true 或 等价于 true 的值的元素创建一个新数组。`callback` 只会在已经赋值的索引上被调用,对于那些已经被删除或者从未被赋值的索引不会被调用。那些没有通过 `callback` 测试的元素会被跳过,不会被包含在新数组中。 <br> ``` function isBigEnough(element) { return element >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44] ``` <br> # Array.prototype.reduce(callback[, initialValue]) 对数组中的每个元素执行一个由您提供的`reducer`函数(升序执行),将其结果汇总为单个返回值。 <br> 回调函数第一次执行时,`accumulator` 和`currentValue`的取值有两种情况:如果调用 `reduce()` 时提供了`initialValue`,`accumulator`取值为`initialValue`,`currentValue`取数组中的第一个值;如果没有提供 `initialValue`,那么`accumulator`取数组中的第一个值,`currentValue`取数组中的第二个值。 * callback:执行数组中每个值的函数,包含四个参数: * accumulator:累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue。 * currentValue:数组中正在处理的元素。 * currentIndex:可选。数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则为1。 * array:可选。调用reduce()的数组 * initialValue:可选。作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。 ``` // 计算数组中每个元素出现的次数 var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; var countedNames = names.reduce(function (allNames, name) { if (name in allNames) { allNames[name]++; } else { allNames[name] = 1; } return allNames; }, {}); // countedNames is: // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 } ``` <br> ``` // 数组去重 let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4]; let result = arr.sort().reduce((init, current)=>{ if(init.length===0 || init[init.length-1]!==current){ init.push(current); } return init; }, []); console.log(result); //[1,2,3,4,5] ``` <br> ``` // 按顺序运行Promise function runPromiseInSequence(arr, input) { return arr.reduce( (promiseChain, currentFunction) => promiseChain.then(currentFunction), Promise.resolve(input) ); } // promise function 1 function p1(a) { return new Promise((resolve, reject) => { resolve(a * 5); }); } // promise function 2 function p2(a) { return new Promise((resolve, reject) => { resolve(a * 2); }); } // function 3 - will be wrapped in a resolved promise by .then() function f3(a) { return a * 3; } // promise function 4 function p4(a) { return new Promise((resolve, reject) => { resolve(a * 4); }); } const promiseArr = [p1, p2, f3, p4]; runPromiseInSequence(promiseArr, 10) .then(console.log); // 1200 ``` <br> ``` // 按属性对object分类 var people = [ { name: 'Alice', age: 21 }, { name: 'Max', age: 20 }, { name: 'Jane', age: 20 } ]; function groupBy(objectArray, property) { return objectArray.reduce(function (acc, obj) { var key = obj[property]; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); return acc; }, {}); } var groupedPeople = groupBy(people, 'age'); // groupedPeople is: // { // 20: [ // { name: 'Max', age: 20 }, // { name: 'Jane', age: 20 } // ], // 21: [{ name: 'Alice', age: 21 }] // } ``` <br> <br> # Array.prototype.reduceRight(callback[, initialValue]) 接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。 ``` const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight( (accumulator, currentValue) => accumulator.concat(currentValue) ); console.log(array1); // expected output: Array [4, 5, 2, 3, 0, 1] ```