javascript - String.prototype 导致循环提前退出

标签 javascript prototype

我定义了一个名为clean的 String.prototype 方法

String.prototype.clean = function() {       
        clean = new Array();
        tokens = [
            ['&', '&'],
            ['"', '"'],
            ["'", '''],
            ['<', '&lt;'],
            ['>', '&gt;']
        ];
        for(i = 0; i < this.length; i++) {      
            s = this[i];

            for(a = 0; a < tokens.length; a++) {
                if(tokens[a][0] == s) {
                    s = tokens[a][1];
                    break;
                }
            }

            clean.push(s);          

        }

        str =  clean.join("");
        return str;
    }

在循环中调用时它似乎可以工作,如下所示:

str = ["<script>", "<", ">"];
    for(i = 0; i < 3; i++) {
        console.log(str[i].clean());
    }

for 循环在第一次调用 clean() 后中断,控制台如下所示:

[2/20/2014 8:19:26 PM] &lt;script&gt; 

为什么会发生这种情况,我在这里做错了什么?

输出除外:

&lt;script&gt;
&lt;
&gt;

最佳答案

你有:

str = ["<script>", "<", ">"];
for(i = 0; i < 3; i++) {
    console.log(str[i].clean());
}

执行时创建一个全局变量i。然后你就有了:

String.prototype.clean = function() {     
    ...
    for(i = 0; i < this.length; i++) {      
    ...
}

它修改全局i的值。始终通过使用 var 声明来将变量保留在适当的上下文中,例如:

for (var i = 0; ...; ...) {

关于javascript - String.prototype 导致循环提前退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21924018/

相关文章:

javascript - 单击链接调用javascript时如何在selenium webdriver中获取href值?

javascript - 在 Babylon.js 中移动网格的问题

javascript - 如何将 jquery tabledit 按钮添加到表的新行

javascript - 在 HTML 中使用 javascript 函数

javascript - 遍历原型(prototype)中的对象

javascript - Rails 服务器/控制台错误 - 没有要加载的文件 - CoffeeScript (LoadError)

c - 这个函数的原型(prototype)看起来如何才能可编译?

javascript - 在这个例子中原型(prototype)的重要性是什么?

javascript - 是否有一种统一的方法可以为单个对象编写多个原型(prototype)函数?

javascript - "Extend"highcharts图表添加属性和功能,原型(prototype)