资讯专栏INFORMATION COLUMN

Javascript 关于array的使用

zombieda / 2596人阅读

摘要:关于深复制详见其他博文方法数组简单用法方法的参数翻译说传入一个回调函数里面有三个参数当前遍历的元素当前元素的坐标以及遍历的数组还有一个可选参数,在里面使用就是这个值如果未传入,则是根据当前执行环境获取。

Javascript 关于array的使用

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

最近做项目经常会使用到数组,尤其在一个中台系统中,数组是尤为常见的,而且前端数组可以实现任何有序数据结构,总结一下数组的方方面面。

使用 创建数组
const arr = [] // 直接申明
const arr1 = new Array() // 使用示例构建
const arr2 = Array()
const arr3 = Array.of(1, 2) // 从多个参数直接构建一个Array
const arr4 = Array.from(likeArr) // 从一个类数组中创建一个数组

上面可以使用Array.from 进行数组深复制。关于深复制详见其他博文

方法
数组简单用法
array 方法的callback 参数


翻译说: 传入一个回调函数callback, callback 里面有三个参数当前遍历的元素element, 当前元素的坐标index, 以及遍历的数组array. 还有一个可选参数,在find里面使用this就是这个值thisArg如果未传入,则是根据当前执行环境获取this。

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


参数看callback参数,返回结果数组中的符合条件的值,如果是对象则返回对象引用。

返回一个array中的值,如果是对象或者数组则返回引用,直接修改会改动数组中的值
Array.prototype.forEach

遍历这个数组,但是在forEach中不可以使用break、continue继续中断后续循环, 如果使用return 后将不再执行return后的语句,也不影响forEach的循环如下图:

Array.prototype.slice

复制数组,可以继续数组浅拷贝(深拷贝和浅拷贝关注后续)

slice 会复制最外层,相似的比如

使用对象展开符号...

slice 传入两个可选参数beginend,返回一个新的数组。如下:

返回一个新数组可以进行数组的链式操作
Array.prototype.concat

连接一个数组或者多个值:

连接一个数组:

返回一个新数组,可以进行数组的链式操作
Array.prototype.from

通过已存在数组进行浅拷贝或者一个类数组的对象转化成数组:

类数组转化:
最明显的类数组,例如查询页面dom:

现在是NodeList,转化成数组:


这样就可以使用所有的数组操作

返回的是数组就可以链式使用方法了
Array.prototype.push

将一个值推入到数组的尾端,并返回新的数组长度。

Array.prototype.pop

将一个值从数组的尾端移除,并返回移除数组中的那个值.

pop 是 push 的反操作。使用push和pop可以实现栈数据结构(先进后出)

Array.prototype.shift

将一个数据从数组的头部移除。并返回移除的值

Array.prototype.unshift

讲一个数据添加到数组的头部,并返回新数组的长度

使用shift和unshift 可以实现队列的数据结构(先进先出)

Array.prototype.indexOf

获取数组中某个值的坐标,只能是字面量变量数组,不适用多维数组和多对象数组

有一个可选参数fromIndex,从fromIndex可是搜索

数组进阶操作
Array.prototype.map

传入一个回调函数,会对数组每个参数执行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

需要两个参数,一个callback参数,一个累加初始值.
callback参数:

callback参数有三个累加的值acc, 当前值cv, 当前坐标cvIdx, 当前数组arr

用法:

求和:

返回值根据初始化的值来变化,可能是数组,对象,数字,字符串等等。

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

对数组继续填充,传入三个变量, 填充值value, 填充开始位置start, 填充结束位置end

返回修改后的数组可以继续操作

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

判断是否存在满足回调函数返回的条件,回调函数条件如上callback 参数,返回值是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

判断数组中每一个是否满足回调函数满足的条件,返回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

过滤满足回调函数返回值的的数组,返回值是一个数组,如果没有满足的则是空数组:

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

数组中是否包含某个值:

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

根据回调函数进行排序,参数:

当什么都不传递的时候,则根据每个字符的Unicode的值

传入一个比较函数的时候:

这里描述几种情况:

如果函数返回小于0,排序前一个值a放到一个小的下标

如果函数返回返回0,则a和b的位置不变

返回值大于0,则排序的后一个值b放到小的下标

比较函数总是要返回相似的值,不一样的值导致返回的结果未必是预料的。

Array.prototype.reverse

数组的反转,直接数组头尾交换:

更换后数组,和变换前数组是同一个对象,同sort函数。

Array.of

传入多个变量,将其转换成新的数组:

一些数组变换操作 使用map

map 可以会数组中每个值进行相同函数操作,例如:
将一个变量中所有id取出来

var persons = [ { id: 3 }, { id: 4 }]
const ids = persons.map(p => p.id)
使用reduce 链式操作

所谓链式操作,就是直接返回数组直接继续使用数组中方法,不熟悉不推荐使用,代码维护性下降
如下:

const idsStr = persons.map(p => p.id).join(",") // 3,4(join返回字符串,可以继续使用字符串方法)
数组关于Promise的sao操作

看如下代码:

Promise.all(ids.map(id => requestPersonById(id)).then(persons => {
    // persons 就是每个id请求的人
})
数组和Set的故事

去重操作:

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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/96492.html

相关文章

  • 关于javascript中类型判断那些疑惑

    摘要:对于复杂类型它的每个实例都有属性。当检测实例时优于因为能检测这段代码是从的。补充以下结果,发现第三种方法也能正确判断出。我们知道结果是那如何判断两个变量呢比较两个变量,使用的即可。 Javascript中数据类型分为两种: 简单数据类型:Undefined, NULL, Boolean, Number, String 复杂数据类型:Object 接下来我们就来看看怎么做数据类型判别...

    李增田 评论0 收藏0
  • 开开心心做几道JavaScript机试题 - 02

    摘要:前集回顾我们在开开心心做几道机试题中吐了槽,也顺势展开了机试题之旅,本章我们暂时压抑自己的吐槽之心,继续就题目前行。其实和都是构造函数,可以直接调用的。请尝试完成一个解析模块本题考查对的理解,各部分都是什么意思。 前集回顾 我们在开开心心做几道JavaScript机试题 - 01中吐了槽,也顺势展开了机试题之旅,本章我们暂时压抑自己的吐槽之心,继续就题目前行。仍然希望对各位正确认识Ja...

    seal_de 评论0 收藏0
  • JavaScript深入浅出

    摘要:理解的函数基础要搞好深入浅出原型使用原型模型,虽然这经常被当作缺点提及,但是只要善于运用,其实基于原型的继承模型比传统的类继承还要强大。中文指南基本操作指南二继续熟悉的几对方法,包括,,。商业转载请联系作者获得授权,非商业转载请注明出处。 怎样使用 this 因为本人属于伪前端,因此文中只看懂了 8 成左右,希望能够给大家带来帮助....(据说是阿里的前端妹子写的) this 的值到底...

    blair 评论0 收藏0
  • JavaScript数组

    摘要:与稀疏数组对立的为密集数组,密集数组的索引会被持续的创建,并且其元素的数量等于其长度。创建一个长度为的数组,并初始化了个元素使用构造函数创建数组对象的时候,关键字是可以省略的。另外使用和删除元素是影响数组的长度的。 说明:本文只总结了JavaScript数组在web端的行为,不包括NodeJs端的行为。本文不涉及类型化数组(TypedArray)的讨论、总结。 一、什么是数组 数组的定...

    HtmlCssJs 评论0 收藏0
  • 关于JavaScript函数柯里化问题探索

    摘要:函数柯里化关于函数柯里化的问题最初是在忍者秘籍中讲闭包的部分中看到的,相信很多同学见过这样一道和柯里化有关的面试题实现一个函数,使得如下断言能够能够通过简单说就是实现一个求值函数,能够将所有参数相加得出结果。方法返回一个表示该对象的字符串。 函数柯里化   关于函数柯里化的问题最初是在《JavaScript忍者秘籍》中讲闭包的部分中看到的,相信很多同学见过这样一道和柯里化有关的面试题:...

    vboy1010 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<