面試題 - 將僞數組轉換爲數組的 N 種方案

今天面試了一我的,竟然不知道如何將僞數組轉換爲數組前端

什麼是僞數組?

  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

clipboard.png

相關文章
相關標籤/搜索