ES6中数组增长了不少新的方法,可是先回顾下以前ES5中的数组的方法。数组
Array.prototype.forEach
遍历一下数组中的每一个选项数据结构
Array.prototype.map, Array.prototype.filter: 返回一个新的数组。
二者的区别是:map返回的是,由原数组中的每一个元素调用一个方法后返回的新数组;filter是经过指定函数测试,而后建立了个新的数组;函数
Array.prototype.some,Array.prototype.every: 返回的是Boolean值
some只要有一个符号就返回;every只要有一个不符合就返回。测试
Array.prototype.reduce, Array.prototype.reduceRight:至关于一个迭代的过程,返回最终的结果。能够传4个参数:previous, current, index, array.this
indexOf, lastIndexOfprototype
这个方法是将对象转为真正的数组,这个对象有两种类型:相似数组的对象和可遍历的对象(如ES6中的Set和Map)code
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']
经常使用的场景对象
常见的相似数组对象是NodeList集合和arguments接口
Array.from('hello');//['h','e','l','l','o'] let namesSet = new Set(['a','b']) Array.from(namesSet);//['a','b'] Array.from([1,2,3])//[1,2,3]
但有一点,扩展运算符(...)也能够将某些数据结构转为数组字符串
var args = [...arguments]; [...document.querySelectorAll('div')]
其实扩展运算符背后调用的是遍历器接口(Symbol.iterator),若是一个对象没有部署成这个接口,就没法转换。Array.from方法则还支持相似的数组对象,可是这种相似数组对象,必需要有length属性,若是没有,就不能转换。
Array.from还能够接受第二个参数,做用相似与数组的map方法,用于对每一个元素进行处理。
这个方式是用于将一组值,转换为数组。
Array.of(3,11,8)//[3,11,8]
这个方法的主要目的,是弥补数组构造函数Array()的不足
new Array(3)//[undefined*3]
Array.of能够替代Array()或者new Array()
Array.of()//[] Array.of(undefined)//[undefined] Array.of(1)//[1] Array.of(1,2)//[1,2]
将制定位置的成员复制到其余位置,而后返回当前数组,就是使用这个方法,修改当前数组。
Array.prototype.copyWithin(target, start = 0, end = this.length)
target(必选):从该位置开始替换数据
start(可选):从该位置开始读取数据,默认为0,若是是负数,表示倒数。
end(可选):到该位置前中止读取数据,默认等于数组长度。若是是负数,表示倒数。
[1,2,3,4,5].copyWidthin(0, 3)//[4,5,3,4,5]
[1,2,3,4,5].copyWidthin(0,3,4)//[3,2,3,4,5]
[1,2,3,4,5].copyWidthin(0,-2,-1)//[4,2,3,4,5]
find(): 用于找到第一个符合条件的数组成员
findIndex(): 返回第一个符合条件的数组成员位置
这个方式使用一个定值,填充一个数组
['a','b','c'].fill(7)//[7,7,7]
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"
这个方法表示某个数组是否包含给定的值
数组的空位,数组的空位和undefined不是同一个概念
0 in [undefined, undefined, undefined] // true 0 in [, , ,] // false
ES5中
forEach,filter,every,some会跳过空位 map会跳过空位,但会保留这个值 join(),toString()会将空位视为undefined,而undefined和null会被处理成空字符串. ES6会将空位转为undefined.