8000 es6 扩展数组方法 · Issue #6 · ZSI2017/blog · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

es6 扩展数组方法 #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the comm 8000 unity.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
ZSI2017 opened this issue Mar 27, 2018 · 0 comments
Open

es6 扩展数组方法 #6

ZSI2017 opened this issue Mar 27, 2018 · 0 comments

Comments

@ZSI2017
Copy link
Owner
ZSI2017 commented Mar 27, 2018

归纳es6 中常用的数组方法。方便平时熟练使用,记忆。


from

将类对象转为真正的数组:比如一些类数组的对象和可遍历的对象

  let arrayLike = {
    "0":'a',
    "1":"b",
    "2":"c",
    length:3
  }
  // ES5 的写法
  var arr1 = [].slice.call(arrayLike);

  // ES6 写法
  var arr2 = Array.from(arrayLike);

或者是 NodeList 集合 和 arguments对象

   var nodeList = document.querySelectorAll("p");
   var newArray = Array.from(nodeList);       // 转换成数组。

  // arguments
  var args = Array.from(arguments);     

of

of 方法用于将一组值,转换为数组。基本上可以用来替代Array() 或者 new Array(),

  Array.of(1,2,3);  // [1,2,3]
  Array.of(1);       //[1]
  Array.of(undefined);  // [undefined]

可以使用下面代码模拟

  function ArrayOf() {
    return [].slice.call(arguments);
  }

copyWithin

Array.prototype.copyWithin(target,start = 0,end = this.length)
包含三个参数:

  • target(必需): 从该位置开始替换,如果为负值,则表示倒数。
  • start(可选): 从该位置开始读取数据,默认为0。负值 表示倒数。
  • end(可选): 从该位置停止读取数据,默认等于数组长度。负值,表示倒数。
 [1,2,3,4,5].copyWithin(0,3,4)   // [4, 2, 3, 4, 5]

 [1, 2, 3, 4, 5].copyWithin(0, -2, -1)    //  [4, 2, 3, 4, 5]

find

数组实例的find方法,用于找出第一个符合条件的数组成员。

  [1,2,3,4].find(function(value,index,arr){
     return value>3
  })
  // 4

接受第二个参数,用来绑定this 值

  var p = {number:3}
  [1,2,3,4,5].find(function(value,index,arr){
      return value>this.number
  },p)
  // 4

findIndex

返回第一个符合条件的数组成员的位置

[1,2,3,4].findIndex(function(value,index,arr){
   return value>3
})
// 3

fill

fill 方法使用给定值,填充一个数组

  new Array(4).fill(4);   // [4, 4, 4, 4]

实现类似 [[1,1...],[2,2...],...[n,n,n...]] 这样的二维数组,里面子数组的值为动态的

  var n = 5;
  new Array(n).fill(2).map(function(value,index){ return new Array(n).fill(index)})

使用ES5写法

 Array.fill = function(number,filler){
   var arr = [];
   for(var i =0;i<number;i++) {
     arr.push(filler)
   }
   return arr;
 }
 Array.fill(4,1)

includes

返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes 方法类似。
ES2016引入该方法

  [1,2,3].includes(1)   // true;
  [1,2,3,NaN].includes(NaN) // true

  // 相对应的 indexOf 就无法检测出 NaN
  [1,2,3,NaN].indexOf(NaN);    // -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant
0