Javascript arguments.sort()抛出错误排序不是一个函数 [英] Javascript arguments.sort() throw error sort is not a function

查看:153
本文介绍了Javascript arguments.sort()抛出错误排序不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Just wondering why i got an error with the following simple JavaScript function

function highest(){ 
  return arguments.sort(function(a,b){ 
    return b - a; 
  }); 
}
highest(1, 1, 2, 3);

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

Error messsage : TypeError: arguments.sort is not a function.

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

I am confused as arguments it is an array (i thought). Please help and explain why. Many thanks

推荐答案

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

Because arguments has no sort method. Be aware that arguments is not an Array object, it's an array-like Arguments object.

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

However, you can use Array.prototype.slice to convert arguments to an array; and then you will be able to use 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]

这篇关于Javascript arguments.sort()抛出错误排序不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆