find、findIndex、forEach

来源:互联网 发布:铁幕演说知乎 编辑:程序博客网 时间:2024/06/07 15:38

语法

arr.find(callback[, thisArg])

实例

var inventory = [    {name: 'apples', quantity: 2},    {name: 'bananas', quantity: 0},    {name: 'cherries', quantity: 5}];function findCherries(fruit) {     return fruit.name === 'cherries';}console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }

在一个数组中查找素数

function isPrime(element, index, array) {  var start = 2;  while (start <= Math.sqrt(element)) {    if (element % start++ < 1) {      return false;    }  }  return element > 1;}console.log([4, 6, 8, 12].find(isPrime)); // undefined, not foundconsole.log([4, 5, 8, 12].find(isPrime)); // 5


源码

if (!Array.prototype.find) {  Array.prototype.find = function(predicate) {    'use strict';    if (this == null) {      throw new TypeError('Array.prototype.find called on null or undefined');    }    if (typeof predicate !== 'function') {      throw new TypeError('predicate must be a function');    }    var list = Object(this);    var length = list.length >>> 0;    var thisArg = arguments[1];    var value;    for (var i = 0; i < length; i++) {      value = list[i];      if (predicate.call(thisArg, value, i, list)) {        return value;      }    }    return undefined;  };}

findIndex语法

arr.findIndex(callback[, thisArg])

实例

function isPrime(element, index, array) {  var start = 2;  while (start <= Math.sqrt(element)) {    if (element % start++ < 1) {      return false;    }  }  return element > 1;}console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not foundconsole.log([4, 6, 7, 12].findIndex(isPrime)); // 2

源码

if (!Array.prototype.findIndex) {  Array.prototype.findIndex = function(predicate) {    'use strict';    if (this == null) {      throw new TypeError('Array.prototype.findIndex called on null or undefined');    }    if (typeof predicate !== 'function') {      throw new TypeError('predicate must be a function');    }    var list = Object(this);    var length = list.length >>> 0;    var thisArg = arguments[1];    var value;    for (var i = 0; i < length; i++) {      value = list[i];      if (predicate.call(thisArg, value, i, list)) {        return i;      }    }    return -1;  };}

forEach语法

arr.forEach(callback[, thisArg])

实例

function logArrayElements(element, index, array) {  console.log('a[' + index + '] = ' + element);}// Notice that index 2 is skipped since there is no item at// that position in the array.[2, 5, , 9].forEach(logArrayElements);// logs:// a[0] = 2// a[1] = 5// a[3] = 9


总数和数组个数

function Counter() {  this.sum = 0;  this.count = 0;}Counter.prototype.add = function(array) {  array.forEach(function(entry) {    this.sum += entry;    ++this.count;  }, this);  // ^---- Note};var obj = new Counter();obj.add([2, 5, 9]);obj.count// 3 obj.sum// 16


一个对象复制函数
function copy(obj) {  var copy = Object.create(Object.getPrototypeOf(obj));  var propNames = Object.getOwnPropertyNames(obj);  propNames.forEach(function(name) {    var desc = Object.getOwnPropertyDescriptor(obj, name);    Object.defineProperty(copy, name, desc);  });  return copy;}var obj1 = { a: 1, b: 2 };var obj2 = copy(obj1); // obj2 looks like obj1 now

如果在迭代期间修改数组,则可能跳过其他元素.

var words = ["one", "two", "three", "four"];words.forEach(function(word) {  console.log(word);  if (word === "two") {    words.shift();  }});// one// two// four

源码
// Production steps of ECMA-262, Edition 5, 15.4.4.18// Reference: http://es5.github.io/#x15.4.4.18if (!Array.prototype.forEach) {  Array.prototype.forEach = function(callback, thisArg) {    var T, k;    if (this === null) {      throw new TypeError(' this is null or not defined');    }    // 1. Let O be the result of calling toObject() passing the    // |this| value as the argument.    var O = Object(this);    // 2. Let lenValue be the result of calling the Get() internal    // method of O with the argument "length".    // 3. Let len be toUint32(lenValue).    var len = O.length >>> 0;    // 4. If isCallable(callback) is false, throw a TypeError exception.     // See: http://es5.github.com/#x9.11    if (typeof callback !== "function") {      throw new TypeError(callback + ' is not a function');    }    // 5. If thisArg was supplied, let T be thisArg; else let    // T be undefined.    if (arguments.length > 1) {      T = thisArg;    }    // 6. Let k be 0    k = 0;    // 7. Repeat, while k < len    while (k < len) {      var kValue;      // a. Let Pk be ToString(k).      //    This is implicit for LHS operands of the in operator      // b. Let kPresent be the result of calling the HasProperty      //    internal method of O with argument Pk.      //    This step can be combined with c      // c. If kPresent is true, then      if (k in O) {        // i. Let kValue be the result of calling the Get internal        // method of O with argument Pk.        kValue = O[k];        // ii. Call the Call internal method of callback with T as        // the this value and argument list containing kValue, k, and O.        callback.call(T, kValue, k, O);      }      // d. Increase k by 1.      k++;    }    // 8. return undefined  };}



0 0