ES6中数组api的扩展

数组在静态方法与实例方法中都有所拓展

Array.from() 
Array.of()
Array.prototype.find()
Array.prototype.findIndex() 
Array.prototype.includes()
Array.prototype.fill() 
Array.prototype.keys()
Array.prototype.values()
 Array.prototype.entries()

Array.from() 将类数组对象(必须有length属性)转成数组,只要部署了Interator接口的数据结构,都可以将其转为数组(set,map,函数内部的arguments对象)

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']
Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']

Array.of() 用于将一组值,转换为数组,如果没有参数,将会返回一个空数组

 Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

Array.prototype.find() 找出第一个符合条件的数组成员,有返回该成员,没有则返回undefined, find方法的函数可以接受三个参数(value,index,arr)即当前的值,当前的位置,元素组

let arr = [1, 2, 4, -3,-4];
let result = arr.find((item, index) => {
console.log(item, index);
return item < 0;
   });
console.log(result);   //-3
let res = [1, 3, 6, 9].find((n) => n > 3);
console.log(res);   //6

Array.prototype.findIndex() 返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

let arr = [1, 2, 4, -3, -5];
let result = arr.findIndex((item, index) => {
//console.log(item, index);
return item < 0;
});
console.log(result);   //3

Array.prototype.includes() 检查某个数组中是否包含给定的值,返回boolean类型的值
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, NaN].includes(NaN) // true

Array.prototype.fill() 使用给定值,填充一个数组

  ['a', 'b', 'c'].fill(7)
 // [7, 7, 7]

new Array(3).fill(7)
// [7, 7, 7]
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']                 表示从一号位置开始,向原数组填充7,到2号位置之前结束

Array.prototype.keys()
Array.prototype.entries()
Array.prototype.values()
三者用于数组遍历

key对键名的遍历,value是对键值的遍历,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"

不适用for...of循环,可以手动调用遍历器对象的next方法,进行遍历

	let letter = ['a', 'b', 'c'];
    let entries = letter.entries();
   console.log(entries.next().value); // [0, 'a']
   console.log(entries.next().value); // [1, 'b']
   console.log(entries.next().value); // [2, 'c']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值