不明白为什么循环运行两次

Can not figure out why loop runs twice

本文关键字:两次 运行 明白 为什么 循环      更新时间:2023-09-26

这似乎很容易,也不应该那么复杂,但两天后我就不知所措了。我不明白为什么这个循环会运行两次。

db = openDatabase("com.xyz.mobile.db", "", "The App Database", 5 * 1024 * 1024);
        db.transaction(function(tx) {
            tx.executeSql("SELECT * FROM somedata", [], function(tx, result) {
                c = (result.rows.length - 1); //result.rows.length = 2 there are only 2 records
                console.log("c = " + c); // outputs 1 in console
                for(var i = 0; i < result.rows.length; i++) {
                    console.log("i = " + i); 
                    console.log(result.rows.item(i)['description']);
                    if(i == c){
                        console.log("I will run twice just to make you pound on key board");
                        break;
                    } 
                } 
            }, null);
        });

以下是我在Chrome控制台中获得的内容:

c = 1
i = 0
2/30/2012 22:02:08
i = 1
2/30/2012 22:02:27
I will run twice just to make you pound on key board
c = 1
i = 0
2/30/2012 22:02:08
i = 1
2/30/2012 22:02:27
I will run twice just to make you pound on key board

帮我欧比旺你是我唯一的希望。

c = 1因此result.rows.length = 2因此for(var i = 0; i < result.rows.length; i++)运行2x,我想你的意思是:for(var i = 0; i < c; i++)

除非你问为什么回调运行两次,在这种情况下,我会得出结论,它被调用了两次。。。

我会做:

db = openDatabase("com.xyz.mobile.db", "", "The App Database", 5 * 1024 * 1024);
console.log('i am here at ' + new Date());
db.transaction(function(tx) {
....

确保您的脚本在中

<head> </head>

不在中的部分

<body> </body>

一切都会好起来的。我的一位同事也遇到了同样的问题,这就是解决办法。我们仍然没有一个正确的答案,为什么它会跑两次,但请尝试一下,让我知道这有帮助。