zoukankan      html  css  js  c++  java
  • from、includes、indexOf

    from、includes、indexOf:https://blog.csdn.net/j59580/article/details/53897630?utm_source=blogxgwz1

    语法

    Array.from(arrayLike[, mapFn[, thisArg]])


    实例

    1.  
      // Array-like object (arguments) to Array
    2.  
      function f() {
    3.  
      return Array.from(arguments);
    4.  
      }
    5.  
       
    6.  
      f(1, 2, 3);
    7.  
      // [1, 2, 3]
    8.  
       
    9.  
       
    10.  
      // Any iterable object...
    11.  
      // Set
    12.  
      var s = new Set(["foo", window]);
    13.  
      Array.from(s);
    14.  
      // ["foo", window]
    15.  
       
    16.  
       
    17.  
      // Map
    18.  
      var m = new Map([[1, 2], [2, 4], [4, 8]]);
    19.  
      Array.from(m);
    20.  
      // [[1, 2], [2, 4], [4, 8]]
    21.  
       
    22.  
       
    23.  
      // String
    24.  
      Array.from("foo");
    25.  
      // ["f", "o", "o"]
    26.  
       
    27.  
       
    28.  
      // Using an arrow function as the map function to
    29.  
      // manipulate the elements
    30.  
      Array.from([1, 2, 3], x => x + x);
    31.  
      // [2, 4, 6]
    32.  
       
    33.  
       
    34.  
      // Generate a sequence of numbers
    35.  
      Array.from({length: 5}, (v, k) => k);
    36.  
      // [0, 1, 2, 3, 4]

    源码

    1.  
      // Production steps of ECMA-262, Edition 6, 22.1.2.1
    2.  
      // Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
    3.  
      if (!Array.from) {
    4.  
      Array.from = (function () {
    5.  
      var toStr = Object.prototype.toString;
    6.  
      var isCallable = function (fn) {
    7.  
      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
    8.  
      };
    9.  
      var toInteger = function (value) {
    10.  
      var number = Number(value);
    11.  
      if (isNaN(number)) { return 0; }
    12.  
      if (number === 0 || !isFinite(number)) { return number; }
    13.  
      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
    14.  
      };
    15.  
      var maxSafeInteger = Math.pow(2, 53) - 1;
    16.  
      var toLength = function (value) {
    17.  
      var len = toInteger(value);
    18.  
      return Math.min(Math.max(len, 0), maxSafeInteger);
    19.  
      };
    20.  
       
    21.  
      // The length property of the from method is 1.
    22.  
      return function from(arrayLike/*, mapFn, thisArg */) {
    23.  
      // 1. Let C be the this value.
    24.  
      var C = this;
    25.  
       
    26.  
      // 2. Let items be ToObject(arrayLike).
    27.  
      var items = Object(arrayLike);
    28.  
       
    29.  
      // 3. ReturnIfAbrupt(items).
    30.  
      if (arrayLike == null) {
    31.  
      throw new TypeError("Array.from requires an array-like object - not null or undefined");
    32.  
      }
    33.  
       
    34.  
      // 4. If mapfn is undefined, then let mapping be false.
    35.  
      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
    36.  
      var T;
    37.  
      if (typeof mapFn !== 'undefined') {
    38.  
      // 5. else
    39.  
      // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
    40.  
      if (!isCallable(mapFn)) {
    41.  
      throw new TypeError('Array.from: when provided, the second argument must be a function');
    42.  
      }
    43.  
       
    44.  
      // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
    45.  
      if (arguments.length > 2) {
    46.  
      T = arguments[2];
    47.  
      }
    48.  
      }
    49.  
       
    50.  
      // 10. Let lenValue be Get(items, "length").
    51.  
      // 11. Let len be ToLength(lenValue).
    52.  
      var len = toLength(items.length);
    53.  
       
    54.  
      // 13. If IsConstructor(C) is true, then
    55.  
      // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
    56.  
      // 14. a. Else, Let A be ArrayCreate(len).
    57.  
      var A = isCallable(C) ? Object(new C(len)) : new Array(len);
    58.  
       
    59.  
      // 16. Let k be 0.
    60.  
      var k = 0;
    61.  
      // 17. Repeat, while k < len… (also steps a - h)
    62.  
      var kValue;
    63.  
      while (k < len) {
    64.  
      kValue = items[k];
    65.  
      if (mapFn) {
    66.  
      A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
    67.  
      } else {
    68.  
      A[k] = kValue;
    69.  
      }
    70.  
      k += 1;
    71.  
      }
    72.  
      // 18. Let putStatus be Put(A, "length", len, true).
    73.  
      A.length = len;
    74.  
      // 20. Return A.
    75.  
      return A;
    76.  
      };
    77.  
      }());
    78.  
      }



    includes语法

    var boolean = array.includes(searchElement[, fromIndex])


    实例

    1.  
      [1, 2, 3].includes(2); // true
    2.  
      [1, 2, 3].includes(4); // false
    3.  
      [1, 2, 3].includes(3, 3); // false
    4.  
      [1, 2, 3].includes(3, -1); // true
    5.  
      [1, 2, NaN].includes(NaN); // true

    源码

    1.  
      if (!Array.prototype.includes) {
    2.  
      Array.prototype.includes = function(searchElement /*, fromIndex*/) {
    3.  
      'use strict';
    4.  
      if (this == null) {
    5.  
      throw new TypeError('Array.prototype.includes called on null or undefined');
    6.  
      }
    7.  
       
    8.  
      var O = Object(this);
    9.  
      var len = parseInt(O.length, 10) || 0;
    10.  
      if (len === 0) {
    11.  
      return false;
    12.  
      }
    13.  
      var n = parseInt(arguments[1], 10) || 0;
    14.  
      var k;
    15.  
      if (n >= 0) {
    16.  
      k = n;
    17.  
      } else {
    18.  
      k = len + n;
    19.  
      if (k < 0) {k = 0;}
    20.  
      }
    21.  
      var currentElement;
    22.  
      while (k < len) {
    23.  
      currentElement = O[k];
    24.  
      if (searchElement === currentElement ||
    25.  
      (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
    26.  
      return true;
    27.  
      }
    28.  
      k++;
    29.  
      }
    30.  
      return false;
    31.  
      };
    32.  
      }

    indexOf语法

    arr.indexOf(searchElement[, fromIndex = 0])

    实例

    1.  
      var array = [2, 9, 9];
    2.  
      array.indexOf(2); // 0
    3.  
      array.indexOf(7); // -1
    4.  
      array.indexOf(9, 2); // 2
    5.  
      array.indexOf(2, -1); // -1
    6.  
      array.indexOf(2, -3); // 0

    查找元素的所有出现

    1.  
      var indices = [];
    2.  
      var array = ['a', 'b', 'a', 'c', 'a', 'd'];
    3.  
      var element = 'a';
    4.  
      var idx = array.indexOf(element);
    5.  
      while (idx != -1) {
    6.  
      indices.push(idx);
    7.  
      idx = array.indexOf(element, idx + 1);
    8.  
      }
    9.  
      console.log(indices);
    10.  
      // [0, 2, 4]


    查找数组中是否存在元素并更新数组

    1.  
      function updateVegetablesCollection (veggies, veggie) {
    2.  
      if (veggies.indexOf(veggie) === -1) {
    3.  
      veggies.push(veggie);
    4.  
      console.log('New veggies collection is : ' + veggies);
    5.  
      } else if (veggies.indexOf(veggie) > -1) {
    6.  
      console.log(veggie + ' already exists in the veggies collection.');
    7.  
      }
    8.  
      }
    9.  
       
    10.  
      var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
    11.  
       
    12.  
      updateVegetablesCollection(veggies, 'spinach');
    13.  
      // New veggies collection is : potato,tomato,chillies,green-papper,spinach
    14.  
      updateVegetablesCollection(veggies, 'spinach');
    15.  
      // spinach already exists in the veggies collection.


    源码

      1.  
        // Production steps of ECMA-262, Edition 5, 15.4.4.14
      2.  
        // Reference: http://es5.github.io/#x15.4.4.14
      3.  
        if (!Array.prototype.indexOf) {
      4.  
        Array.prototype.indexOf = function(searchElement, fromIndex) {
      5.  
         
      6.  
        var k;
      7.  
         
      8.  
        // 1. Let o be the result of calling ToObject passing
      9.  
        // the this value as the argument.
      10.  
        if (this == null) {
      11.  
        throw new TypeError('"this" is null or not defined');
      12.  
        }
      13.  
         
      14.  
        var o = Object(this);
      15.  
         
      16.  
        // 2. Let lenValue be the result of calling the Get
      17.  
        // internal method of o with the argument "length".
      18.  
        // 3. Let len be ToUint32(lenValue).
      19.  
        var len = o.length >>> 0;
      20.  
         
      21.  
        // 4. If len is 0, return -1.
      22.  
        if (len === 0) {
      23.  
        return -1;
      24.  
        }
      25.  
         
      26.  
        // 5. If argument fromIndex was passed let n be
      27.  
        // ToInteger(fromIndex); else let n be 0.
      28.  
        var n = +fromIndex || 0;
      29.  
         
      30.  
        if (Math.abs(n) === Infinity) {
      31.  
        n = 0;
      32.  
        }
      33.  
         
      34.  
        // 6. If n >= len, return -1.
      35.  
        if (n >= len) {
      36.  
        return -1;
      37.  
        }
      38.  
         
      39.  
        // 7. If n >= 0, then Let k be n.
      40.  
        // 8. Else, n<0, Let k be len - abs(n).
      41.  
        // If k is less than 0, then let k be 0.
      42.  
        k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
      43.  
         
      44.  
        // 9. Repeat, while k < len
      45.  
        while (k < len) {
      46.  
        // a. Let Pk be ToString(k).
      47.  
        // This is implicit for LHS operands of the in operator
      48.  
        // b. Let kPresent be the result of calling the
      49.  
        // HasProperty internal method of o with argument Pk.
      50.  
        // This step can be combined with c
      51.  
        // c. If kPresent is true, then
      52.  
        // i. Let elementK be the result of calling the Get
      53.  
        // internal method of o with the argument ToString(k).
      54.  
        // ii. Let same be the result of applying the
      55.  
        // Strict Equality Comparison Algorithm to
      56.  
        // searchElement and elementK.
      57.  
        // iii. If same is true, return k.
      58.  
        if (k in o && o[k] === searchElement) {
      59.  
        return k;
      60.  
        }
      61.  
        k++;
      62.  
        }
      63.  
        return -1;
      64.  
        };
      65.  
        }
  • 相关阅读:
    【USACO】又买饲料 单调队列dp
    数论:px+py 不能表示的最大数为pq-p-q的证明
    codeforces round #419 E. Karen and Supermarket
    [USACO4.1]麦香牛块Beef McNuggets
    【USACO】 录制唱片
    【USACO】 洞穴奶牛
    【USACO】奶牛抗议 树状数组+dp
    【USACO】 奶牛会展
    【LSGDOJ 2015】数页码
    阿里云合作伙伴峰会SaaS加速器专场 | 商业加持,迈进亿元俱乐部
  • 原文地址:https://www.cnblogs.com/bydzhangxiaowei/p/10475624.html
Copyright © 2011-2022 走看看