Javascript arguments.sort()抛出错误排序不是一个函数

Bru*_*uce 9 javascript

只是想知道为什么我使用以下简单的JavaScript函数出错了

function highest(){ 
  return arguments.sort(function(a,b){ 
    return b - a; 
  }); 
}
highest(1, 1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

错误消息:TypeError:arguments.sort不是函数.

我很困惑,因为它是一个数组(我想).请帮忙解释原因.非常感谢

Ori*_*iol 18

因为arguments没有sort方法.请注意,arguments它不是一个Array对象,它是一个类似于数组的Arguments对象.

但是,您可以使用Array.prototype.slice转换arguments为数组; 然后你就可以使用Array.prototype.sort:

function highest(){ 
  return [].slice.call(arguments).sort(function(a,b){ 
    return b - a; 
  }); 
}
highest(1, 1, 2, 3); // [3, 2, 1, 1]
Run Code Online (Sandbox Code Playgroud)

  • 在现代引擎中,您也可以跳过转换为数组,直接使用Array.prototype.sort:`[] .sort.call(arguments,function(a,b){...` (2认同)
  • @Paulpro 我个人不喜欢改变`Arguments` 对象,我更喜欢使用数组而不是类似数组的对象。但确实,`[].sort.call(arguments)` 也应该工作(根据 IETester 甚至在 IE5.5 上工作)。 (2认同)

Ash*_*k R 6

使用扩展语法将参数转换为真正的数组:

   function highest(...arguments){ 
      return arguments.sort(function(a,b){ 
        return b - a; 
      }); 
   }
   highest(1, 1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

输出: (4) [3, 2, 1, 1]

安慰