本文介绍了JavaScript的数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组没有被正确排序。有人可以让我知道我做错了?

My array isn't being sorted properly. Can someone let me know what I am doing wrong?

...
 sortArray = new Array ("hello", "Link to Google", "zFile", "aFile");

//sort array
        if (dir == "asc") { 
            sortArray.sort(function(a,b){return a - b}); 
        } else { 
            sortArray.sort(function(a,b){return b - a});
        }

        for(var i=0; i<sortArray.length; i++) { 
            console.log(sortArray[i]);
        }

的日志显示他们以相同的顺序,因为它们被输入。

the log is showing them in the same order as they were entered.

推荐答案

您想在您的排序比较,而不是减法:

You want to make a comparison in your sort, not a subtraction:

if (dir == "asc") {
    sortArray.sort(function(a, b) {
        return a.toLowerCase() > b.toLowerCase()
    });
} else {
    sortArray.sort(function(a, b) {
        return b.toLowerCase() > a.toLowerCase()
    });
}

我也用与toLowerCase()让链接到谷歌被适当放置。

I also used toLowerCase() so that 'Link to Google' is placed appropriately.

这篇关于JavaScript的数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 07:16