JavaScript unshift 参数返回意外结果

javascript unshift arguments returns unexpected results

本文关键字:意外 结果 返回 参数 unshift JavaScript      更新时间:2023-09-26
router.route = function (alias, pattern, action, constraints) {
   if (2 === arguments.length)
     Array.prototype.unshift.call(arguments, undefined)
   console.log(arguments)
}
router.route('/artist/:id', function () {})

{ '0': undefined,
  '1': '/artist/:id',
  '2': [Function],
  '3': undefined,
  '4': undefined,
  '5': undefined,
  '6': undefined,
  '7': undefined,
  '8': undefined,
  '9': undefined,
  '10': undefined,
  '11': undefined,
  '12': undefined,
  '13': undefined,
  '14': undefined,
  '15': undefined,
  '16': undefined,
  '17': undefined,
  '18': undefined,
  '19': undefined }

我基本上要做的是使"别名"参数可选但我试图找到一种方法来做到这一点而不这样做。

if (2 === arguments.length) {
  action = pattern
  pattern = alias
  alias = undefined
}

所以 unshift() 基本上可以工作,我得到相同的结果。 alias = undefined pattern = '/artist/:id' action = function () {}

但问题是,我突然在参数数组的末尾添加了 17 个"未定义"。

这会影响性能吗,有人知道为什么会这样吗?

编辑

我不小心在我的原始问题中写了 Array.prototype.unshift(参数,未定义

)而不是 Array.prototype.unshift.call(参数,未定义),非常抱歉。

如果由于资源超时而存在这些未定义的位置,那么是的,性能将受到影响。 如果它只是一个空的数组索引,那么 否 它不会影响性能。

如果我理解正确,你不是只想删除数组的第一个元素吗?

如果是这样,您可以执行以下操作:

var args = Array.prototype.shift.call(arguments);