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

Array.prototype.concat()

  • 合并一个或多个数组;
  • 不会覆盖原数组结构;
  • 多个数组的合并,存在相同值不会被覆盖;
  • 数组合并的是对象,那么对象会被加入到数组中去(见示例abk变量)
  • 数组合并的是字符串或者数字,会将字符串或数字加入到数组中去(见示例 abc变量)
//代码
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接收两个参数

  • callback回调函数,接受四个参数
    • 上次回调函数的结果(或初始值(initialValue) ,即reduce方法的第二个参数)
    • 当前正在进行的元素
    • 正在进行中的元素的数组索引,如果没有初始值,则回调从1开始执行
    • 调用 reduce 的数组
  • initialValue 可选项,其值用于第一次调用 callback 的第一个参数。

应用其他场景

// 数组扁平化
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 )

  • 参数 start (可选),原数组索引位置
  • 参数 end (可选),原数组第n个的位置
  • slice( 2, 3 ) 提取原数组索引为2的,直到原数组从左到右的第3个值
  • 如果数组中有 对象引用(不是实际的对象),那么改变该对象引用,相应的新数组与原数组的对象引用也会随之改变(如示例二)

示例一

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()

  • 返回一个字符串,表示指定的数组及其元素。
  • 该方法等同于数组调用了join方法
  • 该方法无参数

示例一

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])

  • find()方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
  • findeIndex()方法,它返回数组中找到的元素的索引,而不是其值。
  • find 方法不会改变数组。
  • 在第一次调用 callback 函数时会确定元素的索引范围,即调用后添加了数组不会被访问到,以及回调函数中未被访问的数组被提前删除,该元素扔然能被访问到

参数

  • callback 数组每一项回调函数,拥有参数:

    • element 当前遍历到的元素。
    • index 当前遍历到的索引。
    • array 数组本身。
  • thisArg( 可选 )— 指定 callback 的 this 参数。

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

返回

  • 当某个元素通过 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;
    }
  });
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容