1

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

显而易见的解决方案:

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

4

5 回答 5

1

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

var queue = [array,of,things,to,do];
while (queue.length) {
    var todo = queue.pop();
    //do something to todo
}
于 2012-05-05T10:04:36.117 回答
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) { 
    ...
}
于 2012-05-05T10:23:54.517 回答
0

这些中的任何一个都可以工作:

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

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

手动跳出循环

var queue = new Queue();
while (queue) {
  queue.size() ? queue.pop() : break;  
}​
于 2012-05-05T10:29:55.647 回答
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以返回不是一些字符串值,而是一个布尔值。

于 2012-05-05T10:39:59.590 回答
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) {}

于 2012-05-05T10:56:50.033 回答