reduceRight、reverse、shift、slice

来源:互联网 发布:淘宝收藏店铺看不到 编辑:程序博客网 时间:2024/06/04 18:58
语法
arr.reduceRight(callback[, initialValue])


实例

var total = [0, 1, 2, 3].reduceRight(function(a, b) {  return a + b;});// total == 6

二维数组转一维数组

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

源码

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

reverse语法

arr.reverse()
实例
var myArray = ['one', 'two', 'three'];myArray.reverse(); console.log(myArray) // ['three', 'two', 'one']

shift语法

arr.shift()

实例

var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];console.log('myFish before: ' + myFish);// "myFish before: angel,clown,mandarin,surgeon"var shifted = myFish.shift(); console.log('myFish after: ' + myFish); // "myFish after: clown,mandarin,surgeon" console.log('Removed this element: ' + shifted); // "Removed this element: angel"

slice语法

arr.slice([begin[, end]])

实例

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];var citrus = fruits.slice(1, 3);// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']// citrus contains ['Orange','Lemon']

使用切片

// Using slice, create newCar from myCar.var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'];var newCar = myCar.slice(0, 2);// Display the values of myCar, newCar, and the color of myHonda//  referenced from both arrays.console.log('myCar = ' + myCar.toSource());console.log('newCar = ' + newCar.toSource());console.log('myCar[0].color = ' + myCar[0].color);console.log('newCar[0].color = ' + newCar[0].color);// Change the color of myHonda.myHonda.color = 'purple';console.log('The new color of my Honda is ' + myHonda.color);// Display the color of myHonda referenced from both arrays.console.log('myCar[0].color = ' + myCar[0].color);console.log('newCar[0].color = ' + newCar[0].color);

一些其他的例子

myCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2,         'cherry condition', 'purchased 1997']newCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2]myCar[0].color = red newCar[0].color = redThe new color of my Honda is purplemyCar[0].color = purplenewCar[0].color = purple

数组对象

function list() {  return Array.prototype.slice.call(arguments);}var list1 = list(1, 2, 3); // [1, 2, 3]
例子二
var unboundSlice = Array.prototype.slice;var slice = Function.prototype.call.bind(unboundSlice);function list() {  return slice(arguments);}var list1 = list(1, 2, 3); // [1, 2, 3]

源码
/** * Shim for "fixing" IE's lack of support (IE < 9) for applying slice * on host objects like NamedNodeMap, NodeList, and HTMLCollection * (technically, since host objects have been implementation-dependent, * at least before ES6, IE hasn't needed to work this way). * Also works on strings, fixes IE < 9 to allow an explicit undefined * for the 2nd argument (as in Firefox), and prevents errors when * called on other DOM objects. */(function () {  'use strict';  var _slice = Array.prototype.slice;  try {    // Can't be used with DOM elements in IE < 9    _slice.call(document.documentElement);  } catch (e) { // Fails in IE < 9    // This will work for genuine arrays, array-like objects,     // NamedNodeMap (attributes, entities, notations),    // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),    // and will not fail on other DOM objects (as do DOM elements in IE < 9)    Array.prototype.slice = function(begin, end) {      // IE < 9 gets unhappy with an undefined end argument      end = (typeof end !== 'undefined') ? end : this.length;      // For native Array objects, we use the native slice function      if (Object.prototype.toString.call(this) === '[object Array]'){        return _slice.call(this, begin, end);       }      // For array like object we handle it ourselves.      var i, cloned = [],        size, len = this.length;      // Handle negative value for "begin"      var start = begin || 0;      start = (start >= 0) ? start : Math.max(0, len + start);      // Handle negative value for "end"      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;      if (end < 0) {        upTo = len + end;      }      // Actual expected size of the slice      size = upTo - start;      if (size > 0) {        cloned = new Array(size);        if (this.charAt) {          for (i = 0; i < size; i++) {            cloned[i] = this.charAt(start + i);          }        } else {          for (i = 0; i < size; i++) {            cloned[i] = this[start + i];          }        }      }      return cloned;    };  }}());



0 0
原创粉丝点击