前端开发攻城狮

JavaScript 数组对象原型方法(一)

2017-04-14  本文已影响0人  未来与传说

Array.prototype.concat()

//代码
let a = ["a","b","c"];
let b = ["c","d","e"];
let c = [1,2,3];
let ab = a.concat(b);
let ac = a.concat(c);
let abc = ["a","b"].concat("c");  
let abk = ["a","b"].concat({k:"123"});

//结果
// a = ["a","b","c"]
// ab = ["a", "b", "c", "c", "d", "e"]
// ac = ["a", "b", "c", 1, 2, 3]
// abc = ["a","b","c"]
// abk = ["a","b",{k:"123"}]

Array.prototype.reduce()

示例1

let sum = [0, 1, 2, 3].reduce(function(result, item) {
        return result + item;
      }, 10);
console.log(sum);

//结果
//16

示例2

// 删除 对象中 id=2的数据
let sum = [{id:1,val:"1"},{id:2,value:"2"},{id:3,value:"3"}].reduce(function(result, item) {
        if(item.id!=2){
          return result.concat(item);
        }else{
          return result;
        }
      }, []);
console.log(sum);

//结果
[{id:1,val:"1"},{id:3,value:"3"}]

reduce接收两个参数

应用其他场景

// 数组扁平化
let arr = [1,[3,4],[5,6],[[7,8,9]]];
function flatten(arrs){
  let newarr = []
      newarr =
      arrs.reduce(function(result,item){
        if( Array.isArray(item) ){
          return result.concat( flatten(item) );
        }else{
          return result.concat(item);
        }
      },[]);
  return   newarr
}
var a = flatten(arr);

Polyfill(垫片)

// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
if (!Array.prototype.reduce) {
  Object.defineProperty(Array.prototype, 'reduce', {
    value: function(callback /*, initialValue*/) {
      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');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0; 

      // Steps 3, 4, 5, 6, 7      
      var k = 0; 
      var value;

      if (arguments.length >= 2) {
        value = arguments[1];
      } else {
        while (k < len && !(k in o)) {
          k++; 
        }

        // 3. If len is 0 and initialValue is not present,
        //    throw a TypeError exception.
        if (k >= len) {
          throw new TypeError( 'Reduce of empty array ' +
            'with no initial value' );
        }
        value = o[k++];
      }

      // 8. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kPresent be ? HasProperty(O, Pk).
        // c. If kPresent is true, then
        //    i.  Let kValue be ? Get(O, Pk).
        //    ii. Let accumulator be ? Call(
        //          callbackfn, undefined,
        //          « accumulator, kValue, k, O »).
        if (k in o) {
          value = callback(value, o[k], k, o);
        }

        // d. Increase k by 1.      
        k++;
      }

      // 9. Return accumulator.
      return value;
    }
  });
}

Array.prototype.slice(start , end)

slice( start , end )

示例一

let arr = ["a","b","c","d","e","f","g"];
     
let r1 =  arr.slice();
let r2 =  arr.slice(2, 5);
let r3 =  arr.slice(3);

// r1 结果为 ["a","b","c","d","e","f","g"];
// r2 结果为 ["c","d","e"]
// r3 结果为 ["d",······]

示例二

// myHonda 是对象引用
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);

// 改变myHonda对象的color属性.
myHonda.color = 'purple';

// myCar 及  newCar对应的color属性会跟着改变

经典场景

// 直接执行 Array.prototype.slice()将会得到结果为一个空数组

// 将 类似数组对象(Array-like)转换为真正的数组
// 如果是obj是对象引用则报错,即不是数组对象无法使用该方法
var obj = {0:"a",1:"c",2:"e",length:3};
      // 原型写法
      Array.prototype.slice.call(obj);
      // 简写形式
      [].slice.call(obj);

代码兼容

/**
* 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: len + start;
           
            // Handle negative value for "end"
            var upTo = (end) ? end : 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;
        };
    }
}());

Array.prototype.toString()

示例一

let  arr = ["abc","efg","myName"];
     arr.toString(); // 方法一
     Array.prototype.toString.call(arr);  //方法二
     arr.join(",");  //方法三
//以上三种方法效果一致---------------------

示例二

// 多维数组(数组中没有对象)与一维数组
let  arr = ["abc",["a","c"],"1","2"];
// 结果
// abc,a,c,1,2
// -------------------------------------
// 多维数组中存在 键值对象的情况
var list = ["abc",["a","c"],"1",{"key":"val"}];
// 结果
// abc,a,c,1,[object Object]

Array.prototype.find(callback[, thisArg])

参数

如果提供了 thisArg 参数,那么它将作为每次 callback 函数执行时的上下文对象,否则上下文对象为 undefined

返回

Polyfill(垫片)

// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return kValue.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return undefined.
      return undefined;
    }
  });
}
上一篇 下一篇

猜你喜欢

热点阅读