JavaScript排序功能

时间:2016-03-11 16:30:38

标签: javascript arrays sorting

尝试使此sort函数断言为true。不知道为什么它不起作用。

function sortThis() {
    var args = [].slice.call(arguments);

    var myArray = ['Toyota', 'bmw', 'mercedes', 'cadillac', 'Ford', '1Mitsubishi', 'buick'];
    for (var i = 0; i < args.length; i++) {
        myArray.sort();
    }
    return myArray;
}

console.assert( sortThis(['apples', '3mango', 'tomatoes', '1blackberries', 'oranges', 'Peaches']) === ['1blackberries', '3mango', 'Peaches', 'apples', 'oranges', 'tomatoes']);

3 个答案:

答案 0 :(得分:0)

无法使用===运算符比较数组。您可以使用Array.prototype.every()将其与辅助函数进行比较,如下所示:

function compareArray(arr1, arr2) {
    return arr1.length === arr2.length && arr1.every(function(o, i) {
        return o === arr2[i];
    });
}

此外,您没有考虑传递给sortThis函数的参数。你需要这样做:

function sortThis(arr) {
    return arr.sort();
}

所以现在你可以断言:

var actual = sortThis(['apples', '3mango', 'tomatoes', '1blackberries', 'oranges', 'Peaches']);
var expected = ['1blackberries', '3mango', 'Peaches', 'apples', 'oranges', 'tomatoes'];
console.assert(compareArray(actual, expected));

答案 1 :(得分:0)

您无法使用SELECT t.session, to_char(t.amount, '"$"9990D99') AS usd , d100, d50, d20, d10, d5, d1 FROM transactions t LEFT JOIN crosstab( $$SELECT session, denom, count(*)::int FROM bills GROUP BY 1,2 ORDER BY 1$$ , $$SELECT unnest ('{100,50,20,10,5,1}'::int[])$$ ) AS ct (session text, d100 int, d50 int, d20 int, d10 int, d5 int, d1 int) USING (session); 运算符比较数组。相反,您必须分别循环并比较每个元素,如下所示:

===

`

答案 2 :(得分:-1)

要比较两个字符串数组,只需使用[].join,这与循环和JSON.stringify相比非常快,因为它是本机支持。

["a", "sad", "day"].join("") === ["a", "sad", "day"].join("")

这是您的代码段

result = ["a", "sad", "day"].join("") === ["a", "sad", "day"].join("");

document.write(result === true ? "Assertion Succeeded" : "Assertion Failed");


document.write('<br/>');


result = ["a", "sad", "day"].sort().join("") === ["a", "sad", "day"].join("");

document.write(result === true ? "Assertion Succeeded" : "Assertion Failed");


document.write('<br/>');


result = ["a", "sad", "day"].sort().join("") === ["a", "sad", "day"].sort().join("");

document.write(result === true ? "Assertion Succeeded" : "Assertion Failed");

`