filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素.     注意: filter() 不会对空数组进行检测.     注意: filter() 不会改变原始数组.…
forEach() 方法对数组的每个元素执行一次提供的函数. 注意: 没有返回一个新数组 并且 没有返回值! 应用场景:为一些相同的元素,绑定事件处理器! const arr = ['a', 'b', 'c']; arr.forEach(function(element) { console.log(element); }); arr.forEach( element => console.log(element)); 语法 callback为数组中每个元素执行的函数,该函数接收三个参数: cu…
reduce函数 reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值. 对数组中的所有元素调用指定的回调函数.该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供. <script> const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => { console.log(accumulator +'|' + currentValue…
ES5 中的数组有这个方法:Array.prototype.filter ,具体使用参考MDN,这里讲一个特殊应用: 回顾下语法: new_array = arr.filter(callback[, thisArg]); callback 用来测试数组的每个元素的函数.调用时使用参数 (element, index, array).返回true表示保留该元素(通过测试),false则不保留. 逻辑上很简单, callback 返回 true 就保留,否则不保留,但是有的时候还可以这么用,如图:…
来源 今年某前端笔试的一道题,大概就是实现一遍filter,包括一个可以改变上下文的要求,其实就是改变this啦,跟原生的filter一样的功能跟参数. 解析 filter的功能就是过滤,传入一个函数作为条件,返回true则将元素加入最终返回的数组中. 实现 Array.prototype.filter = function(cb, context){ context = context || this; //确定上下文,默认为this var len = this.length; //数组的长…
/* 终于解决了IE8不支持数组的indexOf方法 */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (…
摘抄与:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter 概述 filter() 方法使用指定的函数测试所有元素,并创建一个包含所有通过测试的元素的新数组. 语法 var new_arrary = arr.filter(callback[, thisArg]) 参数 callback:用来测试数组的每个元素的函数.调用时使用参数 (element, index…
<!DOCTYPE html><html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style type="text…
Array.prototype.map() 1 语法 const new_array = arr.map(callback[, thisArg]) 2 简单栗子 let arr = [1, 5, 10, 15]; let newArr = arr.map(function(x) { return x * 2; }); // arr is now [2, 10, 20, 30] // newArr is still [1, 5, 10, 15] 3 参数说明 callback 生成新数组元素的函数…
1. filter() 方法:创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素 ——filter() 不会对空数组进行检测 ——filter() 不会改变原始数组 2. 语法: array.filter(function(currentValue,index,arr), thisValue) ——function(currentValue, index,arr):必须.函数,数组中的每个元素都会执行这个函数 >>currentValue:必须.当前元素的值 >>…