of、pop、push、reduce

来源:互联网 发布:盘点世界程序员 编辑:程序博客网 时间:2024/05/21 00:00
语法
Array.of(element0[, element1[, ...[, elementN]]])


实例

Array.of(1);         // [1]Array.of(1, 2, 3);   // [1, 2, 3]Array.of(undefined); // [undefined]

源码

if (!Array.of) {  Array.of = function() {    return Array.prototype.slice.call(arguments);  };}

pop语法

arr.pop()

实例

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];console.log(myFish); // ['angel', 'clown', 'mandarin', 'sturgeon']var popped = myFish.pop();console.log(myFish); // ['angel', 'clown', 'mandarin' ] console.log(popped); // 'sturgeon'

push语法

arr.push(element1, ..., elementN)

实例
var sports = ['soccer', 'baseball'];var total = sports.push('football', 'swimming');console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']console.log(total);  // 4

合并两个数组

var vegetables = ['parsnip', 'potato'];var moreVegs = ['celery', 'beetroot'];// Merge the second array into the first one// Equivalent to vegetables.push('celery', 'beetroot');Array.prototype.push.apply(vegetables, moreVegs);console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

使用数组中的对象方式

var obj = {    length: 0,    addElem: function addElem (elem) {        // obj.length is automatically incremented every time an element is added.        [].push.call(this, elem);    }};// Let's add some empty objects just to illustrate.obj.addElem({});obj.addElem({});console.log(obj.length);// → 2

reduce语法
arr.reduce(callback[, initialValue])

实例

var maxCallback = ( pre, cur ) => Math.max( pre.x, cur.x );var maxCallback2 = ( max, cur ) => Math.max( max, cur );// reduce() without initialValue[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }[                      ].reduce( maxCallback ); // TypeError// map/reduce; better solution, also works for empty arrays[ { x: 22 }, { x: 42 } ].map( el => el.x ).reduce( maxCallback2, -Infinity );

计算总和

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {  return previousValue + currentValue;});

也可以这样用

[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr );

再或者这样

[0,1,2,3,4].reduce( (previousValue, currentValue, currentIndex, array) => {  return previousValue + currentValue;}, 10);
求和,数组的所有值
var total = [0, 1, 2, 3].reduce(function(a, b) {  return a + b;}, 0);// total == 6
另一种用法

var total = [ 0, 1, 2, 3 ].reduce( ( acc, cur ) => acc + cur, 0 );


二维数组转一维数组

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {  return a.concat(b);}, []);// flattened is [0, 1, 2, 3, 4, 5]

源码

// Production steps of ECMA-262, Edition 5, 15.4.4.21// Reference: http://es5.github.io/#x15.4.4.21if (!Array.prototype.reduce) {  Array.prototype.reduce = function(callback /*, initialValue*/) {    'use strict';    if (this === null) {      throw new TypeError('Array.prototype.reduce called on null or undefined');    }    if (typeof callback !== 'function') {      throw new TypeError(callback + ' is not a function');    }    var t = Object(this), len = t.length >>> 0, k = 0, value;    if (arguments.length == 2) {      value = arguments[1];    } else {      while (k < len && !(k in t)) {        k++;       }      if (k >= len) {        throw new TypeError('Reduce of empty array with no initial value');      }      value = t[k++];    }    for (; k < len; k++) {      if (k in t) {        value = callback(value, t[k], k, t);      }    }    return value;  };}



0 0