Array.prototype.slice.call() & Array.from()的应用和理解

2,421 阅读1分钟

Array.prototype.slice.call() 可将类数组(arguments,NodeList),字符串(String)转换成数组。

Array.from() 可将类数组(arguments,NodeList),可迭代对象(Set,Map),字符串(String)转换成数组。

Array.prototype.slice.call() 的常用示例

Array.prototype.slice.call(arrayLike, start, end) 将类数组arrayLike转换为数组,并且从下标start开始到下标为end截取数组。

function makeArray (arrayLike) {
    return Array.prototype.slice.call(arrayLike);
}
function doSomething() {
    var args = makeArray(arguments);
    // 使用args
    ...
}

上述示例中,将slice()方法执行时的this值设置为类数组对象(arguments),而slice()对象只需是数值型索引和length属性就能够正常运行,即任何类数组对象(arguments)都能被转换为数组, 例如下面对象就可转换为数组:

var obj = {0:'hello',1:'world',length:2};
console.log(Array.prototype.slice.call(obj)); // ["hello", "world"]

而没有length属性的对象则不能

var obj = {0:'hello',1:'world'}; // 没有length属性
console.log(Array.prototype.slice.call(obj)); // []

Array.from() 的常用示例

Array.from(arrayLike, mapFn, thisArg) --> Array.from(arrayLike).map(fn(), thisArg)

示例1——将类数组转化为数组

function doSomething () {
    var args = Array.from(arguments);
    // 使用args
    ...
}

此方法为ECMAScript6新方法,更简洁清晰的将类数组对象转化为数组。

Array.from()方法调用会基于arguments对象中的元素创建一个新的数组,args是Array的一个实例,包含arguments对象中同位置的相同值。

示例2——将Set集合转化为数组

let arr = [1,2,3,4,5,6,7,8,9]
let set = new Set(arr)
console.log(Array.from(set) // [1,2,3,4,5,6,7,8,9]

示例3——将map集合转化为数组

const myMap = new Map().set(true, 7)
console.log(myMap); // Map(1) {true => 7}
console.log(Array.from(myMap)) // [[true,7]]
// 如需变为一维数组可
console.log(Array.from(myMap).flat()) // [true ,7]