首页 > 为什么使用 arguments 方法后的数组不能重新排序?

为什么使用 arguments 方法后的数组不能重新排序?

代码如下:

function where(arr, num) {
    var arr1=Array.prototype.slice.call(arguments,0);
    arr1.sort(function(a,b){
    return b-a;
  });
  alert(arr1);
}

where([3, 10, 5], 3);

输出的结果是 3,10,5,3 ;怎么才能输出 3,3,5,10 ?


function where(arr, num) {
    var arr1=Array.prototype.slice.call(arguments,0);
    var array = [];
    arr1.map(function(item){
        array = array.concat(item);
    });


    array.sort(function(a,b){
        return a-b;
    });
    alert(array);
}

where([3, 10, 5], 3);

先把数组展开吧,而且你用了 alert,自动调用了 toString 方法,不然也不是 3 10 5 3 。。

不知道你的数组嵌套层数,可以参考下 underscore 的 flatten 方法 https://github.com/hanzichi/u...

【热门文章】
【热门文章】