from

从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例

// 将伪数组转换成真正的数组
function add() {
    // es5
    // let arr = [].slice.call(arguments)
	// ES6
    let arr = Array.from(arguments);
    // 也可通过扩展运算符
    // let arr = [...arguments];
}
add(1, 2, 3);

接受第二个参数,对每个元素进行处理

let arr = Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]

of

将任意的数据类型,转换到数组中

Array.of(3, 11, "22", [1,2,3], {id: 1}) // [3, 11, "22", Array(3), {…}]

copywithin

将数组内部指定位置的元素复制到其他的位置,返回当前数组

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

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

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

find/findIndex

find接收一个回调函数,返回数组中满足条件的第一个值,findIndex返回数组中满足条件的第一个值的索引

let num = [1, 2, -10, -20].find(n => n < 0) // -10
let numIndex = [1, 2, -10, -20].findIndex(n => n < 0) // 2

遍历器

使用entries() / keys() / values() 返回一个遍历器,可以使用for…of循环进行遍历

let arr = ['a', 'b'];
for(let index of arr.keys()) { // 遍历键名,即数组下标
    console.log(index); 
}
// 0 
// 1
for(let ele of arr.values()) {
    console.log(ele); 
}
// a
// b
for(let [index, ele] of arr.entries()) {
    console.log(index, ele); 
}
// 0 "a"
// 1 "b"

let it = arr.entries();
console.log(it.next().value); // [0, "a"]
console.log(it.next().value); // [1, "b"]
console.log(it.next().value); // undefined

includes

返回一个布尔值,表示某个数组是否包含给定的值

console.log([1,2,3].includes(2)); // true
console.log([1,2,3].includes(4)); // false

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

ES6中Promise与async的使用 上一篇
ES6拓展的对象功能 下一篇