浅析"对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

相关文章
相关标签/搜索