亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

Javascript 關(guān)于array的使用

zombieda / 2759人閱讀

摘要:關(guān)于深復(fù)制詳見其他博文方法數(shù)組簡單用法方法的參數(shù)翻譯說傳入一個(gè)回調(diào)函數(shù)里面有三個(gè)參數(shù)當(dāng)前遍歷的元素當(dāng)前元素的坐標(biāo)以及遍歷的數(shù)組還有一個(gè)可選參數(shù),在里面使用就是這個(gè)值如果未傳入,則是根據(jù)當(dāng)前執(zhí)行環(huán)境獲取。

Javascript 關(guān)于array的使用

來自: https://luoyangfu.com/detail/...

最近做項(xiàng)目經(jīng)常會(huì)使用到數(shù)組,尤其在一個(gè)中臺(tái)系統(tǒng)中,數(shù)組是尤為常見的,而且前端數(shù)組可以實(shí)現(xiàn)任何有序數(shù)據(jù)結(jié)構(gòu),總結(jié)一下數(shù)組的方方面面。

使用 創(chuàng)建數(shù)組
const arr = [] // 直接申明
const arr1 = new Array() // 使用示例構(gòu)建
const arr2 = Array()
const arr3 = Array.of(1, 2) // 從多個(gè)參數(shù)直接構(gòu)建一個(gè)Array
const arr4 = Array.from(likeArr) // 從一個(gè)類數(shù)組中創(chuàng)建一個(gè)數(shù)組

上面可以使用Array.from 進(jìn)行數(shù)組深復(fù)制。關(guān)于深復(fù)制詳見其他博文

方法
數(shù)組簡單用法
array 方法的callback 參數(shù)


翻譯說: 傳入一個(gè)回調(diào)函數(shù)callback, callback 里面有三個(gè)參數(shù)當(dāng)前遍歷的元素element, 當(dāng)前元素的坐標(biāo)index, 以及遍歷的數(shù)組array. 還有一個(gè)可選參數(shù),在find里面使用this就是這個(gè)值thisArg如果未傳入,則是根據(jù)當(dāng)前執(zhí)行環(huán)境獲取this。

Array.prototype.find 用法
const a = [1, 2, 4]
const value = a.find(current => current > 3)
console.log(value) // 4
參數(shù)


參數(shù)看callback參數(shù),返回結(jié)果數(shù)組中的符合條件的值,如果是對(duì)象則返回對(duì)象引用。

返回一個(gè)array中的值,如果是對(duì)象或者數(shù)組則返回引用,直接修改會(huì)改動(dòng)數(shù)組中的值
Array.prototype.forEach

遍歷這個(gè)數(shù)組,但是在forEach中不可以使用break、continue繼續(xù)中斷后續(xù)循環(huán), 如果使用return 后將不再執(zhí)行return后的語句,也不影響forEach的循環(huán)如下圖:

Array.prototype.slice

復(fù)制數(shù)組,可以繼續(xù)數(shù)組淺拷貝(深拷貝和淺拷貝關(guān)注后續(xù))

slice 會(huì)復(fù)制最外層,相似的比如

使用對(duì)象展開符號(hào)...

slice 傳入兩個(gè)可選參數(shù)beginend,返回一個(gè)新的數(shù)組。如下:

返回一個(gè)新數(shù)組可以進(jìn)行數(shù)組的鏈?zhǔn)讲僮?/pre>
Array.prototype.concat

連接一個(gè)數(shù)組或者多個(gè)值:

連接一個(gè)數(shù)組:

返回一個(gè)新數(shù)組,可以進(jìn)行數(shù)組的鏈?zhǔn)讲僮?/pre>
Array.prototype.from

通過已存在數(shù)組進(jìn)行淺拷貝或者一個(gè)類數(shù)組的對(duì)象轉(zhuǎn)化成數(shù)組:

類數(shù)組轉(zhuǎn)化:
最明顯的類數(shù)組,例如查詢頁面dom:

現(xiàn)在是NodeList,轉(zhuǎn)化成數(shù)組:


這樣就可以使用所有的數(shù)組操作

返回的是數(shù)組就可以鏈?zhǔn)绞褂梅椒?/pre>
Array.prototype.push

將一個(gè)值推入到數(shù)組的尾端,并返回新的數(shù)組長度。

Array.prototype.pop

將一個(gè)值從數(shù)組的尾端移除,并返回移除數(shù)組中的那個(gè)值.

pop 是 push 的反操作。使用push和pop可以實(shí)現(xiàn)棧數(shù)據(jù)結(jié)構(gòu)(先進(jìn)后出)

Array.prototype.shift

將一個(gè)數(shù)據(jù)從數(shù)組的頭部移除。并返回移除的值

Array.prototype.unshift

講一個(gè)數(shù)據(jù)添加到數(shù)組的頭部,并返回新數(shù)組的長度

使用shift和unshift 可以實(shí)現(xiàn)隊(duì)列的數(shù)據(jù)結(jié)構(gòu)(先進(jìn)先出)

Array.prototype.indexOf

獲取數(shù)組中某個(gè)值的坐標(biāo),只能是字面量變量數(shù)組,不適用多維數(shù)組和多對(duì)象數(shù)組

有一個(gè)可選參數(shù)fromIndex,從fromIndex可是搜索

數(shù)組進(jìn)階操作
Array.prototype.map

傳入一個(gè)回調(diào)函數(shù),會(huì)對(duì)數(shù)組每個(gè)參數(shù)執(zhí)行callback:

polyfill(mdn)
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {

  Array.prototype.map = function(callback/*, thisArg*/) {

    var T, A, k;

    if (this == null) {
      throw new TypeError("this is null or not defined");
    }

    // 1. Let O be the result of calling ToObject passing the |this| 
    //    value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal 
    //    method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if (typeof callback !== "function") {
      throw new TypeError(callback + " is not a function");
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (arguments.length > 1) {
      T = arguments[1];
    }

    // 6. Let A be a new array created as if by the expression new Array(len) 
    //    where Array is the standard built-in constructor with that name and 
    //    len is the value of len.
    A = new Array(len);

    // 7. Let k be 0
    k = 0;

    // 8. Repeat, while k < len
    while (k < len) {

      var kValue, mappedValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal 
      //    method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal 
        //    method of O with argument Pk.
        kValue = O[k];

        // ii. Let mappedValue be the result of calling the Call internal 
        //     method of callback with T as the this value and argument 
        //     list containing kValue, k, and O.
        mappedValue = callback.call(T, kValue, k, O);

        // iii. Call the DefineOwnProperty internal method of A with arguments
        // Pk, Property Descriptor
        // { Value: mappedValue,
        //   Writable: true,
        //   Enumerable: true,
        //   Configurable: true },
        // and false.

        // In browsers that support Object.defineProperty, use the following:
        // Object.defineProperty(A, k, {
        //   value: mappedValue,
        //   writable: true,
        //   enumerable: true,
        //   configurable: true
        // });

        // For best browser support, use the following:
        A[k] = mappedValue;
      }
      // d. Increase k by 1.
      k++;
    }

    // 9. return A
    return A;
  };
}
Array.prototype.reduce

需要兩個(gè)參數(shù),一個(gè)callback參數(shù),一個(gè)累加初始值.
callback參數(shù):

callback參數(shù)有三個(gè)累加的值acc, 當(dāng)前值cv, 當(dāng)前坐標(biāo)cvIdx, 當(dāng)前數(shù)組arr

用法:

求和:

返回值根據(jù)初始化的值來變化,可能是數(shù)組,對(duì)象,數(shù)字,字符串等等。

polyfill(mdn)
// 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.fill

對(duì)數(shù)組繼續(xù)填充,傳入三個(gè)變量, 填充值value, 填充開始位置start, 填充結(jié)束位置end

返回修改后的數(shù)組可以繼續(xù)操作

polyfill(來自mdn)
if (!Array.prototype.fill) {
  Object.defineProperty(Array.prototype, "fill", {
    value: function(value) {

      // Steps 1-2.
      if (this == null) {
        throw new TypeError("this is null or not defined");
      }

      var O = Object(this);

      // Steps 3-5.
      var len = O.length >>> 0;

      // Steps 6-7.
      var start = arguments[1];
      var relativeStart = start >> 0;

      // Step 8.
      var k = relativeStart < 0 ?
        Math.max(len + relativeStart, 0) :
        Math.min(relativeStart, len);

      // Steps 9-10.
      var end = arguments[2];
      var relativeEnd = end === undefined ?
        len : end >> 0;

      // Step 11.
      var final = relativeEnd < 0 ?
        Math.max(len + relativeEnd, 0) :
        Math.min(relativeEnd, len);

      // Step 12.
      while (k < final) {
        O[k] = value;
        k++;
      }

      // Step 13.
      return O;
    }
  });
}
Array.prototype.some

判斷是否存在滿足回調(diào)函數(shù)返回的條件,回調(diào)函數(shù)條件如上callback 參數(shù),返回值是true/false

polyfill(mdn)
if (!Array.prototype.some) {
  Array.prototype.some = function(fun/*, thisArg*/) {
    "use strict";

    if (this == null) {
      throw new TypeError("Array.prototype.some called on null or undefined");
    }

    if (typeof fun !== "function") {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length >>> 0;

    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t && fun.call(thisArg, t[i], i, t)) {
        return true;
      }
    }

    return false;
  };
}
Array.prototype.every

判斷數(shù)組中每一個(gè)是否滿足回調(diào)函數(shù)滿足的條件,返回true/false

polyfill(mdn)
if (!Array.prototype.every) {
  Array.prototype.every = function(callbackfn, thisArg) {
    "use strict";
    var T, k;

    if (this == null) {
      throw new TypeError("this is null or not defined");
    }

    // 1. Let O be the result of calling ToObject passing the this 
    //    value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal method
    //    of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
    if (typeof callbackfn !== "function") {
      throw new TypeError();
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (arguments.length > 1) {
      T = thisArg;
    }

    // 6. Let k be 0.
    k = 0;

    // 7. Repeat, while k < len
    while (k < len) {

      var kValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal 
      //    method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal method
        //    of O with argument Pk.
        kValue = O[k];

        // ii. Let testResult be the result of calling the Call internal method
        //     of callbackfn with T as the this value and argument list 
        //     containing kValue, k, and O.
        var testResult = callbackfn.call(T, kValue, k, O);

        // iii. If ToBoolean(testResult) is false, return false.
        if (!testResult) {
          return false;
        }
      }
      k++;
    }
    return true;
  };
}
Array.prototype.filter

過濾滿足回調(diào)函數(shù)返回值的的數(shù)組,返回值是一個(gè)數(shù)組,如果沒有滿足的則是空數(shù)組:

polyfill(mdn)
if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    "use strict";

    if (this === void 0 || this === null) {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function") {
      throw new TypeError();
    }

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method"s new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }

    return res;
  };
}
Array.prototype.includes

數(shù)組中是否包含某個(gè)值:

polyfill(mdn)
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, "includes", {
    value: function(searchElement, fromIndex) {

      // 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 len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === "number" && typeof y === "number" && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1. 
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}
Array.prototype.sort

根據(jù)回調(diào)函數(shù)進(jìn)行排序,參數(shù):

當(dāng)什么都不傳遞的時(shí)候,則根據(jù)每個(gè)字符的Unicode的值

傳入一個(gè)比較函數(shù)的時(shí)候:

這里描述幾種情況:

如果函數(shù)返回小于0,排序前一個(gè)值a放到一個(gè)小的下標(biāo)

如果函數(shù)返回返回0,則a和b的位置不變

返回值大于0,則排序的后一個(gè)值b放到小的下標(biāo)

比較函數(shù)總是要返回相似的值,不一樣的值導(dǎo)致返回的結(jié)果未必是預(yù)料的。

Array.prototype.reverse

數(shù)組的反轉(zhuǎn),直接數(shù)組頭尾交換:

更換后數(shù)組,和變換前數(shù)組是同一個(gè)對(duì)象,同sort函數(shù)。

Array.of

傳入多個(gè)變量,將其轉(zhuǎn)換成新的數(shù)組:

一些數(shù)組變換操作 使用map

map 可以會(huì)數(shù)組中每個(gè)值進(jìn)行相同函數(shù)操作,例如:
將一個(gè)變量中所有id取出來

var persons = [ { id: 3 }, { id: 4 }]
const ids = persons.map(p => p.id)
使用reduce 鏈?zhǔn)讲僮?/b>

所謂鏈?zhǔn)讲僮?,就是直接返回?cái)?shù)組直接繼續(xù)使用數(shù)組中方法,不熟悉不推薦使用,代碼維護(hù)性下降
如下:

const idsStr = persons.map(p => p.id).join(",") // 3,4(join返回字符串,可以繼續(xù)使用字符串方法)
數(shù)組關(guān)于Promise的sao操作

看如下代碼:

Promise.all(ids.map(id => requestPersonById(id)).then(persons => {
    // persons 就是每個(gè)id請(qǐng)求的人
})
數(shù)組和Set的故事

去重操作:

const arr = [...new Set(duplicateArr)]

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/96492.html

相關(guān)文章

  • 關(guān)于javascript中類型判斷那些疑惑

    摘要:對(duì)于復(fù)雜類型它的每個(gè)實(shí)例都有屬性。當(dāng)檢測實(shí)例時(shí)優(yōu)于因?yàn)槟軝z測這段代碼是從的。補(bǔ)充以下結(jié)果,發(fā)現(xiàn)第三種方法也能正確判斷出。我們知道結(jié)果是那如何判斷兩個(gè)變量呢比較兩個(gè)變量,使用的即可。 Javascript中數(shù)據(jù)類型分為兩種: 簡單數(shù)據(jù)類型:Undefined, NULL, Boolean, Number, String 復(fù)雜數(shù)據(jù)類型:Object 接下來我們就來看看怎么做數(shù)據(jù)類型判別...

    李增田 評(píng)論0 收藏0
  • 開開心心做幾道JavaScript機(jī)試題 - 02

    摘要:前集回顧我們?cè)陂_開心心做幾道機(jī)試題中吐了槽,也順勢展開了機(jī)試題之旅,本章我們暫時(shí)壓抑自己的吐槽之心,繼續(xù)就題目前行。其實(shí)和都是構(gòu)造函數(shù),可以直接調(diào)用的。請(qǐng)嘗試完成一個(gè)解析模塊本題考查對(duì)的理解,各部分都是什么意思。 前集回顧 我們?cè)陂_開心心做幾道JavaScript機(jī)試題 - 01中吐了槽,也順勢展開了機(jī)試題之旅,本章我們暫時(shí)壓抑自己的吐槽之心,繼續(xù)就題目前行。仍然希望對(duì)各位正確認(rèn)識(shí)Ja...

    seal_de 評(píng)論0 收藏0
  • JavaScript深入淺出

    摘要:理解的函數(shù)基礎(chǔ)要搞好深入淺出原型使用原型模型,雖然這經(jīng)常被當(dāng)作缺點(diǎn)提及,但是只要善于運(yùn)用,其實(shí)基于原型的繼承模型比傳統(tǒng)的類繼承還要強(qiáng)大。中文指南基本操作指南二繼續(xù)熟悉的幾對(duì)方法,包括,,。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。 怎樣使用 this 因?yàn)楸救藢儆趥吻岸耍虼宋闹兄豢炊?8 成左右,希望能夠給大家?guī)韼椭?...(據(jù)說是阿里的前端妹子寫的) this 的值到底...

    blair 評(píng)論0 收藏0
  • JavaScript數(shù)組

    摘要:與稀疏數(shù)組對(duì)立的為密集數(shù)組,密集數(shù)組的索引會(huì)被持續(xù)的創(chuàng)建,并且其元素的數(shù)量等于其長度。創(chuàng)建一個(gè)長度為的數(shù)組,并初始化了個(gè)元素使用構(gòu)造函數(shù)創(chuàng)建數(shù)組對(duì)象的時(shí)候,關(guān)鍵字是可以省略的。另外使用和刪除元素是影響數(shù)組的長度的。 說明:本文只總結(jié)了JavaScript數(shù)組在web端的行為,不包括NodeJs端的行為。本文不涉及類型化數(shù)組(TypedArray)的討論、總結(jié)。 一、什么是數(shù)組 數(shù)組的定...

    HtmlCssJs 評(píng)論0 收藏0
  • 關(guān)于JavaScript函數(shù)柯里化問題探索

    摘要:函數(shù)柯里化關(guān)于函數(shù)柯里化的問題最初是在忍者秘籍中講閉包的部分中看到的,相信很多同學(xué)見過這樣一道和柯里化有關(guān)的面試題實(shí)現(xiàn)一個(gè)函數(shù),使得如下斷言能夠能夠通過簡單說就是實(shí)現(xiàn)一個(gè)求值函數(shù),能夠?qū)⑺袇?shù)相加得出結(jié)果。方法返回一個(gè)表示該對(duì)象的字符串。 函數(shù)柯里化 ??關(guān)于函數(shù)柯里化的問題最初是在《JavaScript忍者秘籍》中講閉包的部分中看到的,相信很多同學(xué)見過這樣一道和柯里化有關(guān)的面試題:...

    vboy1010 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

閱讀需要支付1元查看
<