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開始執(zhí)行
    • 調用 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屬性會跟著改變

經典場景

// 直接執(zhí)行 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 函數執(zhí)行時的上下文對象面哥,否則上下文對象為 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;
    }
  });
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末尚卫,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子尸红,更是在濱河造成了極大的恐慌吱涉,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件驶乾,死亡現場離奇詭異邑飒,居然都是意外死亡,警方通過查閱死者的電腦和手機级乐,發(fā)現死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進店門疙咸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人风科,你說我怎么就攤上這事撒轮。” “怎么了贼穆?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵题山,是天一觀的道長。 經常有香客問我故痊,道長顶瞳,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮慨菱,結果婚禮上焰络,老公的妹妹穿的比我還像新娘。我一直安慰自己符喝,他們只是感情好闪彼,可當我...
    茶點故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著协饲,像睡著了一般畏腕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上茉稠,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天描馅,我揣著相機與錄音,去河邊找鬼战惊。 笑死流昏,一個胖子當著我的面吹牛扎即,可吹牛的內容都是我干的吞获。 我是一名探鬼主播,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼谚鄙,長吁一口氣:“原來是場噩夢啊……” “哼各拷!你這毒婦竟也來了?” 一聲冷哼從身側響起闷营,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤烤黍,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后傻盟,有當地人在樹林里發(fā)現了一具尸體速蕊,經...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年娘赴,在試婚紗的時候發(fā)現自己被綠了规哲。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡诽表,死狀恐怖唉锌,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情竿奏,我是刑警寧澤袄简,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站涩蜘,受9級特大地震影響册烈,放射性物質發(fā)生泄漏茬末。R本人自食惡果不足惜变姨,卻給世界環(huán)境...
    茶點故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一吕粹、第九天 我趴在偏房一處隱蔽的房頂上張望伍纫。 院中可真熱鬧,春花似錦昂芜、人聲如沸莹规。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽良漱。三九已至,卻和暖如春欢际,著一層夾襖步出監(jiān)牢的瞬間母市,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工损趋, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留患久,地道東北人。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓浑槽,卻偏偏與公主長得像蒋失,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子桐玻,可洞房花燭夜當晚...
    茶點故事閱讀 45,047評論 2 355

推薦閱讀更多精彩內容