JavaScript中的遍历详解(多种遍历)(2)

Array.prototype.map(callback(currentValue, index, array){ // do something }[,thisArg]); ``` ```js // map 的一个坑 [1,2,3].map(parseInt); // [1, NaN, NaN] // 提示 map(currentValue,index,array) // parseInt(value,base)

一些有用的数组内置方法(类似 map,回调函数的参数都是那 3 个)

Array.prototype.every(callback[,thisArg]): 测试数组的各个元素是否通过了回调函数的测试,若都通过,返回 true,否则返回 false(说地本质点儿,就是如果回调函数每次返回的值都是 true 的话,则 every() 返回 true,否则为 false)

Array.prototype.filter(callback[,thisArg]): 返回一个新数组,数组的元素是原数组中通过测试的元素(就是回调函数返回 true 的话,对应的元素会进入新数组)

Array.prototype.find(callback[,thisArg]): 返回第一个通过测试的元素

Array.prototype.findIndex(callback[,thisArg]): 与上面函数类似,只不过这个是返回索引

Array.prototype.some(callback[,thisArg]): 类似 find() ,只不过它不返回元素,只返回一个布尔值。只要找到一个通过测试的,就返回 true

Array.prototype.reduce(callback,[initialValue]): 习惯性称之为累加器函数,对数组的每个元素执行回调函数,最后返回一个值(这个值是最后一次调用回调函数时返回的值)

这个函数的回调函数有 4 个参数

accumulator: 上一次调用回调函数返回的值

currentValue: 当前在处理的值

currentIndex

array

initialValue: 可选项,其值用于第一次调用 callback 的第一个参数

Array.prototype.reduceRight(callback[, initialValue]): 用法和上面的函数一样,只不过遍历方向正好相反

// 一些相关的案例 // 对数组进行累加、累乘等运算 [1,10,5,3,8].reduce(function(accumulator,currentValue){ return accumulator*currentValue; }); // 1200 // 数组扁平化 [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) { return a.concat(b); }); // [0, 1, 2, 3, 4, 5] [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { return a.concat(b); }); // [4, 5, 2, 3, 0, 1]

总结一下上面这些函数的共性

都是通过每次的回调函数的返回值进行逻辑操作或判断的

回调函数都可以写成更简洁的箭头函数(推荐)

都可以通过形如 Array.prototype.map.call(str,callback) 的方式来操作字符串

var str = '123,hello'; // 反转字符串 Array.prototype.reduceRight.call(str,function(a,b){ return a+b; }); // olleh,321 // 过滤字符串,只保留小写字母 Array.prototype.filter.call('123,hello', function(a) { return /[a-z]/.test(a); }).join(''); // hello // 利用 map 遍历字符串(这个例子明显举得不太好 *_*) Array.prototype.map.call(str,function(a){ return a.toUpperCase(); }); // ["1", "2", "3", ",", "H", "E", "L", "L", "O"]

最下面的文章想说的就是让我们用更简洁的语法(比如内置函数)遍历数组,从而消除循环结构。

参考资料:无循环 JavaScript

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwyzwg.html