简体   繁体   English

String.prototype导致循环提前退出

[英]String.prototype causing loop to exit early

I have defined a method of String.prototype called clean 我已经定义了一种称为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;
    }

It seems to work when called in a loop, like this: 像这样在循环中调用时,它似乎可以工作:

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

The for loop breaks after the first call to clean() and the console looks like this: 在第一次调用clean()之后,for循环中断,控制台如下所示:

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

Why is this happening, and what am I doing wrong here? 为什么会发生这种情况,我在这里做错了什么?

Output excepted: 输出除外:

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

Here is a very fast way to do the same: 这是执行此操作的快速方法:

var __entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
};

String.prototype.toHtml = function() {
    return String(this).replace(/[&<>"'\/]/g, function (s) {  
        return __entityMap[s];
    });
}

I have yet to find a quicker way.... 我还没有找到更快的方法。

You have: 你有:

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

which creates a global variable i when executed. 在执行时会创建一个全局变量i You then have: 然后,您将拥有:

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

which modifies the value of the global i . 这修改了全局i的值。 Always keep variables in an appropriate context by declaring with var , eg: 始终通过使用var声明将变量保持在适当的上下文中,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM