在条件中计算对象 false

Evaluating an object false within a conditional

本文关键字:对象 false 计算 条件      更新时间:2023-09-26

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

显而易见的解决方案:

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 中显示的这种(精确)语法?如果是这样,如何?

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

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

是否有可能实现这种(精确的)语法

我的回答是:不。

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

免责声明:这只是一些解谜,而不是现实世界的代码。

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) {}触发。

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) { 
    ...
}

这样的事情应该可以工作:

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,返回的不是某个字符串值,而是布尔值。

以下任一都可以:

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

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

手动脱离循环

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