淺析"對arguments對象使用Array.prototype.slice()能夠將其轉化爲數組"

背景

《Javascript高級程序設計(第3版)》的250頁有一句話叫「對arguments對象使用Array.prototype.slice()能夠將其轉化爲數組」,爲何這麼說?html

arguments

Js中的每個函數(箭頭函數除外)自動得到兩個變量this和arguments。所以隨便定義一個非箭頭函數,能夠打印出它的auguments;前端

> function add (a, b) { return arguments;}
> var arg = add (1, 2);
> arg  // 打印arg複製代碼

打印結果
git

arg並非一個數組,可是能夠經過arg[0],arg[1]及arg.length來獲取參數的一些屬性。能夠經過Array.prototype.slice()來將其轉化爲一個數組github

上圖中能夠看出如下兩點:數組

1.Array.prototype.slice()返回一個新數組
2.Array.prototype.slice()並不會影響其參數bash

Array.prototype.slice()

Array.prototype.slice是怎麼實現返回一個新數組的呢?網上也有一些經過看源碼來解析其原理的文章,例如 www.cnblogs.com/henryli/p/3… ,可是做爲一個前端這個理解起來有必定的困難,個人建議是查看loadash對slice的實現來理解一下其原理。
文檔:lodash.think2011.net/slice
源碼:github.com/lodash/loda…函數

_.slice(array, [start=0], [end=array.length])
建立一個裁剪後的數組,從 start 到 end 的位置,但不包括 end 自己的位置。 ui

/**
 * Creates a slice of `array` from `start` up to, but not including, `end`.
 *
 * **Note:** This method is used instead of
 * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
 * returned.
 *
 * @since 3.0.0
 * @category Array
 * @param {Array} array The array to slice.
 * @param {number} [start=0] The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns the slice of `array`.
 */
function slice(array, start, end) {
  let length = array == null ? 0 : array.length
  if (!length) {
    return []
  }
  start = start == null ? 0 : start
  end = end === undefined ? length : end

  if (start < 0) {
    start = -start > length ? 0 : (length + start)
  }
  end = end > length ? length : end
  if (end < 0) {
    end += length
  }
  length = start > end ? 0 : ((end - start) >>> 0)
  start >>>= 0

  let index = -1
  const result = new Array(length)
  while (++index < length) {
    result[index] = array[index + start]
  }
  return result
}複製代碼

所以當咱們使用Array.prototype.slice.call(arg, 0)時,實際上返回了一個新的數組result,該數組的長度等於arg.length,其元素包含從0到arg.length的全部元素,即arg[0],arg[1]this

相關文章
相關標籤/搜索