在条件中评估对象为false

时间:2012-05-05 10:02:02

标签: javascript

假设我们已经定义了一个队列对象,我们希望在队列中有项目时循环。

显而易见的解决方案:

var queue = new Queue();
// populate queue
while (queue.size()) {
    queue.pop();
}

所需的表格:

var queue = new Queue();
// populate queue
while (queue) { // should stop when queue's size is 0
    queue.pop();
}

是否有可能在第二个示例javascript中显示此(确切)语法?如果是这样,怎么样?

5 个答案:

答案 0 :(得分:1)

它必须是一个对象吗?为什么不使用数组?

var queue = [array,of,things,to,do];
while (queue.length) {
    var todo = queue.pop();
    //do something to todo
}

答案 1 :(得分:0)

var MyClass = function(){

   this.CanOperate; 
   //value should be false when nothing can be done with this class instance
};


Use var obj = new MyClass();

while (obj.CanOperate) { 
    ...
}

答案 2 :(得分:0)

其中任何一个都可行:

销毁队列,从而满足条件要求

var queue = new Queue();
while (queue) {
  queue.size() ? queue.pop() : queue = null;  
}​

手动摆脱循环

var queue = new Queue();
while (queue) {
  queue.size() ? queue.pop() : break;  
}​

答案 3 :(得分:0)

这样的事情应该有效:

function Queue() {}
Queue.prototype.toString = function() {
    // I'm using "this.queue" as if it were an array with your actions
    return !!this.queue.length;
};

var queue = new Queue();

// Populate queue

while ( queue ) {
    queue.pop();
}

我们的想法是覆盖toString以返回一些字符串值,而不是布尔值。

答案 4 :(得分:0)

  

是否可以实现此(确切)语法

我的回答是:不。

我尝试了以下方法来解决这个谜语,但它似乎没有用 但我认为这是要走的路。

免责声明:这只是一些谜题解决方案,而不是真实世界的代码。

var Queue = function () {};
Queue.prototype.sizeValue = 2;
Queue.prototype.size = function () 
{
    return this.sizeValue;
};
Queue.prototype.pop = function () 
{
    // EDIT: yes, it's not popping anything.
    // it just reduces size to make toString()
    // and valueOf() return nulls.
    this.sizeValue -= 1;
};
Queue.prototype.valueOf = function () 
{
    if (this.size() > 0) {
        return this.sizeValue;
    }
    return null;
};
Queue.prototype.toString = function () 
{
    if (this.size() > 0) {
        return "Queue["+this.sizeValue+"]";
    }
    return null;
};


var test = new Queue();
while (test) {
    test.pop();
    if (test.size() < -1) {
        // just to get you out of the loop while testing
        alert("failed");
        break;
    }
}
alert("out:"+test);

将警报放在toString()和valueOf()中,看它们是否被条件while (test) {}触发。