小于和大于10 [英] Less than and greater than 10

查看:65
本文介绍了小于和大于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;
   }
}

我尝试过的事情是设置一个间隔来改变变量为0ms(最终成为浏览器默认值),使obj成为一个生命函数,每次使用时都会递增一个全局变量,以及一大堆其他看似不太有用的方法。这里有什么想法,或者指出一些我不知道明显的东西?

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. Any ideas here, or pointers for something obvious I'm missing?

推荐答案

线索在变量名称obj中。比较对象时,他们的 valueOf()<调用/ code> 方法。如果我们提供 valueOf 方法,每次都返回一个不同的值:

The clue is in the variable name "obj". When objects are compared, their valueOf() method is called. If we supply a valueOf method that returns a different value every time:

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() ) );

上述对象的 toValue 在第一次调用时返回9(9 <10),从那时开始返回11(11> 10)。

The above object's toValue returns 9 the first time it's called (9 < 10) and 11 from then on (11 > 10).

这篇关于小于和大于10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆