标题几乎说明了一切。在使用<
,>
,<=
和>=
运算符时,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"
答案 0 :(得分:2)