标题基本概括了所有内容。 JavaScript 在使用时是否保证对象的总顺序<
, >
, <=
and >=
运营商?
我编写了一些代码只是为了检查某些对象的总排序。结果与全序一致,但这并不能证明任何事情:
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"
取决于我们正在考虑的对象。如果我们将注意力集中在类别上numbers https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number,那么是的,订单将是总的。正如您的示例所示,(至少某些)也可以这样说strings https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String。但整体性似乎并不普遍成立。
例如,如果您添加var h = 5;
到您的声明中,然后添加h
给你的thereIsTotalOrder
致电,您将得到false
。那是因为在一个状态下h = 5
and c = 'foo'
, (h
≤c
∨ c
≤h
)为假(这意味着totality http://en.wikipedia.org/wiki/Total_relation不满意)。
正如您正确指出的那样,虽然没有返回错误值thereIsTotalOrder
不prove所有对象都是完全有序的,存在false
value does证明所有对象之间的顺序(如果定义)不是全部的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)