es6数组方法扩充

扩展运算符...

  • 扩展运算符就好比rest运算符的逆运算,将数组转化用逗号隔开的参数序列
  • 替代函数的apply,见下列例子:
例子1:
// ES5 的写法
Math.max.apply(null, [14, 3, 77])

// ES6 的写法
Math.max(...[14, 3, 77])

// 等同于
Math.max(14, 3, 77);

Math.max.call(null,...[14, 3, 77])

例子2:
// ES5的 写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);

// ES6 的写法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
// 或者
Array.prototype.push.call(arr1, ...arr2);
  • 复制数组,见下列例子 不过都是浅拷贝,使用时注意
// es5
 var arr1 = [1,2];
 var arr2 = arr1.concat();
 //或者,等等方法
 var arr2 = arr1.slice();

//es6
//写法一
let arr2 = [...arr1];
// 写法二
let [...a2] = a1;

  • 合并数组,见下列例子:
// es5
let arr1 = [1, 2];
let arr2 = [3, 4];
let arr3=arr1.concat(arr2);

//es6
let arr3=[...arr1, ...arr2];
  • 与解构赋值结合
// ES5
a = list[0], rest = list.slice(1)
// ES6
[a, ...rest] = list
  • 另外注意:扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错,见例子:
const [...butLast, last] = [1, 2, 3, 4, 5];
// 报错

const [first, ...middle, last] = [1, 2, 3, 4, 5];
// 报错
  • 将字符串转成数组:
[...'hello']   //  [h, e, l, l, o]

Array.from()将类数组的对象转成数组

  • 注意一定要是类数组的对象,key为数组的index,并且最后一项是对象的obj.key()的长度
let arrayLike = {
    '0': 'a',  
    '1': 'b',
    '2': 'c',
    length: 3
};

// ES5的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

// ES6的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
  • 常见的类数组的对象有:DOM 操作返回的 NodeList 集合、argument对象,都可以通过该方法转成数组

*Iterator 接口的数据结构,Array.from都能将其转为数组

  • 字符串和 Set 结构都具有 Iterator 接口
Array.from('zhan')  // ['z','h','a','n']

let namesSet = new Set(['a', 'b'])
Array.from(namesSet)        //['a', 'b']
  • 扩展运算符(...)也可以将某些数据结构转为数组
  • 扩展运算符背后调用的是遍历器接口(Symbol.iterator),如果一个对象没有部署这个接口,就无法转换。
// arguments对象
function foo() {
  const args = [...arguments];
}

// NodeList对象
[...document.querySelectorAll('div')]
  • 提供map方法,第二个参数就是类似数组的map方法:
例子一:
let spans = document.querySelectorAll('span.name');

// map()
let names1 = Array.prototype.map.call(spans, s => s.textContent);

// Array.from()
let names2 = Array.from(spans, s => s.textContent)

例子二:
Array.from({ length: 2 }, () => 'jack')
// ['jack', 'jack']

Array.of() 将一组值,转换为数组

Array.of(1,2,3)  // [1,2,3]
  • 其实该方法是弥补Array方法
// Array传入不同的参数个数,结果不一样
Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

数组实例的 copyWithin(target,start,end)

  • Array.prototype.copyWithin(target, start = 0, end = this.length)
  • 它接受三个参数。
    • target(必需):从该位置开始替换数据。如果为负值,表示倒数。
    • start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。
    • end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
// 从数组的第一个开始替换,截取的替换数据从index为3开始到结尾,包前不包后
[1, 2, 3, 4, 5].copyWithin(0, 3)

find()、findIndex()

  • 这两个方法都可以接受第二个参数,用来绑定回调函数的this对象。
例子一:
[1, 4, -5, 10].find((n) => n < 0)

例子二:
[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2

例子三:
function f(v){
  return v > this.age;
}
let person = {name: 'John', age: 20};
[10, 12, 26, 15].find(f, person); 

fill(item,start,end)填充

  • item要填充的值
  • start 从数组的那一个index起始
  • end 结束index
  • start和end可以省略
['a','b','c'].fill(10) // [10,10,10]
['a','b','c'].fill(10,1,2) // ['a',10,'c']
['a','b','c'].fill(10,1) // ['a',10,10]

entries(),keys() 和 values()

  • keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。
for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b

includes()

  • Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似
  • 该方法的第二个参数表示搜索的起始位置
  • indexOf 有两大缺点:
    1. 不够语义化
    2. 内部使用===严格等于,这会导致对NaN的误判
[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN)
[1, 2, 3].includes(2,2)     // false
[NaN].indexOf(NaN)  // -1

数组实例的 flat(),flatMap()

  • 数组的成员有时还是数组,Array.prototype.flat()用于将嵌套的数组“拉平”,变成一维的数组。该方法返回一个新数组,对原数据没有影响。
[1, 2, [3, 4]].flat() // [1,2,3,4]
[1, 2, [3, [4, 5]]].flat(2) //[1,2,3,4,5]
//如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数
[1, [2, [3]]].flat(Infinity) // [1,2,3]

//flatMap
[2, 3, 4].flatMap((x) => [x, x * 2])  //[2,4,3,6,4,8]

数组的空位

  • 数组的空位指,数组的某一个位置没有任何值。比如,Array构造函数返回的数组都是空位。
Array(3) // [, , ,]
  • 注意,空位不是undefined,一个位置的值等于undefined,依然是有值的。空位是没有任何值,in运算符可以说明这一点
0 in [undefined, undefined, undefined] // true
0 in [, , ,] // false
  • es5中数组的个方法对空位的处理
    • forEach(), filter(), reduce(), every() 和some()都会跳过空位。
    • map()会跳过空位,但会保留这个值
    • join()和toString()会将空位视为undefined,而undefined和null会被处理成空字符串。
  • ES6 则是明确将空位转为undefined
  • 由于空位的处理规则非常不统一,所以建议避免出现空位。

转载于:https://my.oschina.net/u/3407699/blog/2221597

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值