简体   繁体   English

小于和大于10

[英]Less than and greater than 10

I'm working on a random code challenge, and I cannot figure out for the life of me how this would be possible 我正在进行随机代码挑战,我无法弄清楚我的生活将如何成为可能

function(obj) {
   if ( (obj < 10) && (obj > 10) ) {
     return true;
   }
}

Things I've tried are setting an interval to change the variable at 0ms(which ends up being browser default), making obj an life function that increments a global variable every time it's used, and a whole bunch of other seemingly less useful approaches. 我尝试过的事情是设置一个间隔来将变量更改为0ms(最终成为浏览器默认值),使obj成为一个生命函数,每次使用时都会递增一个全局变量,以及一大堆其他看似不太有用的方法。 Any ideas here, or pointers for something obvious I'm missing? 这里有任何想法,或指出一些我不知道的明显事物吗?

The clue is in the variable name "obj". 线索在变量名称“obj”中。 When objects are compared, their valueOf() method is called. 比较对象时,将调用其valueOf()方法。 If we supply a valueOf method that returns a different value every time: 如果我们提供一个valueOf方法,每次返回一个不同的值:

 function test(obj) { if ( (obj < 10) && (obj > 10) ) { return true; } } var Obj = function() { var flag = false; this.valueOf = function() { if( flag ) { return 11; } flag = true; return 9; } } console.log( test( new Obj() ) ); 

The above object's toValue returns 9 the first time it's called (9 < 10) and 11 from then on (11 > 10). 上面的对象的toValue在第一次被调用时返回9(9 <10),从那时开始返回11(11> 10)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM