关于javascript:面试题-将伪数组转换为数组的-N-种方案

4次阅读

共计 1203 个字符,预计需要花费 4 分钟才能阅读完成。

明天面试了一个人,竟然不晓得如何将 伪数组转换为数组

什么是伪数组?

  1. length 属性,而且也是数值下标的对象。
  2. 不具备 Array.prototype 上的办法

常见伪数组

  1. arguments
  2. document.getElementsByClassName
  3. $('div')

伪数组转换为数组

输入伪数组

function fun(a,b,c = 1){
    arr = arguments
    console.log(
        typeof arr,
        Array.isArray(arr),
        arr.length,
        arr.slice,
        arr,
    )
fun(3, 2)

应用 Array.from(ES6+)(babel-polyfill)

function fun(a,b,c = 1){arr = Array.from(arguments)
    console.log(
        typeof arr,
        Array.isArray(arr),
        arr.length,
        arr.slice,
        arr,
    )
fun(3, 2)

应用 ... 开展运算符(ES6+)(babel)

function fun(a,b,c = 1){arr = [...arguments]
    console.log(
        typeof arr,
        Array.isArray(arr),
        arr.length,
        arr.slice,
        arr,
    )
fun(3, 2)

应用 slice 和 call 的计划

function fun(a,b,c = 1){arr = Array.prototype.slice.call(arguments)
    console.log(
        typeof arr,
        Array.isArray(arr),
        arr.length,
        arr.slice,
        arr,
    )
    arr = Array.prototype.slice.apply(arguments)
    console.log(
        typeof arr,
        Array.isArray(arr),
        arr.length,
        arr.slice,
        arr,
    )
    arr = [].slice.call(arguments)
    console.log(
        typeof arr,
        Array.isArray(arr),
        arr.length,
        arr.slice,
        arr,
    )
    arr = [].slice.apply(arguments)
    console.log(
        typeof arr,
        Array.isArray(arr),
        arr.length,
        arr.slice,
        arr,
    )
}
fun(3, 2)

循环遍历(兼容性无敌,奢侈不)

function fun(a,b,c = 1){arr = [];
    for(var i = 0,length = arguments.length; i < length; i++) {arr.push(arguments[i]);
    }
    console.log(
        typeof arr,
        Array.isArray(arr),
        arr.length,
        arr.slice,
        arr,
    )
}
fun(3, 2)

微信公众号:前端 linong

正文完
 0