【问题标题】:javascript unshift arguments returns unexpected resultsjavascript unshift 参数返回意外结果
【发布时间】:2023-04-08 03:09:02
【问题描述】:
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(arguments, undefined) 而不是 Array.prototype.unshift.call(arguments, undefined),非常抱歉。

【问题讨论】:

  • 我会在 unshift 之前查看 console.log(参数)显示的内容。
  • 这将在您将 unshift 应用于参数对象时发生。 [].unshift(arguments, 'string') 将导致相同的行为。

标签: javascript node.js


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    如果是这样,你可以这样做:

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

    【讨论】:

    • 我认为 OP 想要相反的结果。 alias 参数是可选的,所以如果只传递了 3 个 args,则假定 alias 被忽略了,因此需要将传递的值移到其正确的参数中,而 alias 未定义。跨度>
    猜你喜欢
    • 2013-03-31
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多