这个标题说明了一切。JavaScript在使用<、>、<=和>=运算符时是否保证对象的总顺序?
我编写了一些代码,只是为了检查某些对象的总体顺序。结果与全序一致,但这并不能证明任何事情:
function thereIsTotalOrder(items){
var one, other, theThird;
// warning: n^3 complexity follows
// If a <= b and b <= a then a = b (antisymmetry);
for(var i=0; i<items.length; i++){
for(var j=0; j<items.length; j++){
one = items[i];
other = items[j];
if((one <= other) && (other <= one) && (one != other)){
return false;
}
}
}
// If a <= b and b <= c then a <= c (transitivity)
for(var i=0; i<items.length; i++){
for(var j=0; j<items.length; j++){
for(var k=0; k<items.length; k++){
one = items[i];
other = items[j];
theThird = items[k];
if((one <= other) && (other <= theThird) && !(one <= theThird)) {
return false;
}
}
}
}
// a <= b or b <= a (totality).
for(var i=0; i<items.length; i++){
for(var j=0; j<items.length; j++){
one = items[i];
other = items[j];
if(!((one <= other) || (other <= one))) {
return false;
}
}
}
return true;
}
function a(){};
function b(){};
var c = "foo";
var d = "bar";
var e = "bar";
var f = function(){};
var g = {name : "bananas"};
console.log(thereIsTotalOrder([a, b, c, d, e, f, g])); // prints "true"发布于 2015-02-08 04:46:04
https://stackoverflow.com/questions/28390401
复制相似问题