JavaScript 數(shù)組對象原型方法(一)

Array.prototype.concat()

  • 合并一個或多個數(shù)組;
  • 不會覆蓋原數(shù)組結(jié)構(gòu);
  • 多個數(shù)組的合并,存在相同值不會被覆蓋;
  • 數(shù)組合并的是對象,那么對象會被加入到數(shù)組中去(見示例abk變量)
  • 數(shù)組合并的是字符串或者數(shù)字,會將字符串或數(shù)字加入到數(shù)組中去(見示例 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"});

//結(jié)果
// 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()

  • 數(shù)據(jù)累加
  • 數(shù)組迭代、遞歸
  • 刪除數(shù)組中的某個元素

示例1

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

//結(jié)果
//16

示例2

// 刪除 對象中 id=2的數(shù)據(jù)
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);

//結(jié)果
[{id:1,val:"1"},{id:3,value:"3"}]

reduce接收兩個參數(shù)

  • callback回調(diào)函數(shù),接受四個參數(shù)
    • 上次回調(diào)函數(shù)的結(jié)果(或初始值(initialValue) ,即reduce方法的第二個參數(shù))
    • 當(dāng)前正在進(jìn)行的元素
    • 正在進(jìn)行中的元素的數(shù)組索引,如果沒有初始值,則回調(diào)從1開始執(zhí)行
    • 調(diào)用 reduce 的數(shù)組
  • initialValue 可選項,其值用于第一次調(diào)用 callback 的第一個參數(shù)。

應(yīng)用其他場景

// 數(shù)組扁平化
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)

  • 提取數(shù)組,不修改原數(shù)組
  • 淺拷貝(一維數(shù)組是對象或數(shù)組,改變提取出的數(shù)組它的對象原數(shù)組也會被改變,如示例二)

slice( start , end )

  • 參數(shù) start (可選),原數(shù)組索引位置
  • 參數(shù) end (可選),原數(shù)組第n個的位置
  • slice( 2, 3 ) 提取原數(shù)組索引為2的,直到原數(shù)組從左到右的第3個值
  • 如果數(shù)組中有 對象引用(不是實際的對象),那么改變該對象引用,相應(yīng)的新數(shù)組與原數(shù)組的對象引用也會隨之改變(如示例二)

示例一

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 結(jié)果為 ["a","b","c","d","e","f","g"];
// r2 結(jié)果為 ["c","d","e"]
// r3 結(jié)果為 ["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對應(yīng)的color屬性會跟著改變

經(jīng)典場景

// 直接執(zhí)行 Array.prototype.slice()將會得到結(jié)果為一個空數(shù)組

// 將 類似數(shù)組對象(Array-like)轉(zhuǎn)換為真正的數(shù)組
// 如果是obj是對象引用則報錯,即不是數(shù)組對象無法使用該方法
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()

  • 返回一個字符串,表示指定的數(shù)組及其元素。
  • 該方法等同于數(shù)組調(diào)用了join方法
  • 該方法無參數(shù)

示例一

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

示例二

// 多維數(shù)組(數(shù)組中沒有對象)與一維數(shù)組
let  arr = ["abc",["a","c"],"1","2"];
// 結(jié)果
// abc,a,c,1,2
// -------------------------------------
// 多維數(shù)組中存在 鍵值對象的情況
var list = ["abc",["a","c"],"1",{"key":"val"}];
// 結(jié)果
// abc,a,c,1,[object Object]

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

  • find()方法返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的值。否則返回 undefined
  • findeIndex()方法,它返回數(shù)組中找到的元素的索引,而不是其值。
  • find 方法不會改變數(shù)組。
  • 在第一次調(diào)用 callback 函數(shù)時會確定元素的索引范圍,即調(diào)用后添加了數(shù)組不會被訪問到,以及回調(diào)函數(shù)中未被訪問的數(shù)組被提前刪除,該元素扔然能被訪問到

參數(shù)

  • callback 數(shù)組每一項回調(diào)函數(shù),擁有參數(shù):

    • element 當(dāng)前遍歷到的元素。
    • index 當(dāng)前遍歷到的索引。
    • array 數(shù)組本身。
  • thisArg( 可選 )— 指定 callback 的 this 參數(shù)。

如果提供了 thisArg 參數(shù),那么它將作為每次 callback 函數(shù)執(zhí)行時的上下文對象,否則上下文對象為 undefined

返回

  • 當(dāng)某個元素通過 callback 的檢驗時,返回數(shù)組中的這個元素的值,否則返回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;
    }
  });
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,327評論 6 537
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,996評論 3 423
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,316評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,406評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,128評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,524評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,576評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,759評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,310評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,065評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,249評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,821評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,479評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,909評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,140評論 1 290
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,984評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,228評論 2 375

推薦閱讀更多精彩內(nèi)容