[英]Replacement for > and < operator
Is there a replacement for the greater/less than operator (<,>)?是否可以替代大于/小于运算符 (<,>)?
I am trying to sort my array on descending order here but i cannot use the operators in the environment i am working in.我试图在这里按降序对我的数组进行排序,但我无法在我工作的环境中使用这些运算符。
Here is the code that i use to order my array with strings in it on descending order:这是我用来按降序对包含字符串的数组进行排序的代码:
// descending order
animals.sort(function (a, b) {
if (a > b) {
return -1;
}
if (b > a) {
return 1;
}
return 0;
});
console.log(animals);
// ["elephant", "dog", "cat", "bee", "ant"]
You can use the localeCompare
function您可以使用
localeCompare
函数
var animals = ["dog", "cat", "ant", "bee", "elephant"]; animals.sort(function (a, b) { return -a.localeCompare(b); }); console.log(animals);
Assuming it's not about the operators , but the characters, you can try假设它不是关于运算符,而是关于字符,您可以尝试
animals.sort(new Function("a", "b", "return (b \u003e a) - (a \x3e b)"));
where \>
and \\x3e
are escape sequences for the >
character in an eval
ed string.其中
\>
\\x3e
和\\x3e
是eval
ed 字符串中>
字符的转义序列。
use sort method of array使用数组的排序方法
var animals = ["elephant", "dog", "cat", "bee", "ant"];
animals.sort();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.