为什么String.Prototype替换在嵌套函数中不起作用?

时间:2015-09-11 15:13:48

标签: javascript string replace string-split

我在同一个脚本文件中声明了以下子字符串替换函数:

String.prototype.replaceAt = function(index, character) {
    index = parseInt(index, 10);
    return this.substr(0, index) + character + this.substr(index + character.length);
}

如果我在主脚本文件中使用此函数(例如在声明之后),它可以正常使用字符串输出。

如果我在嵌套函数中使用此函数,更确切地说,我在另一个函数中有一个函数,我在第二个函数中调用“replaceAt”,它不起作用,它会在“index”中指定的“index”后截断所有字符replaceAt”。我还指定这是Chrome扩展程序中的内容脚本。

示例(在主文件中的函数外部正常工作):

var h = '000000';
h = h.replaceAt(3, "1");
console.log(h);

示例(截断“index”之后的所有内容):

function do_lut() {
    temp = '000000000000000';

    function nfu_change(e, i) {
        if (e.checked) {
            if (temp != null) {
                console.log(i + " - " + temp);
                temp = temp.replaceAt(i, "1");
            } else { temp = '000000000000000'.replaceAt(i, "1"); } 
                       }
        else { if(temp!=null) {temp = temp.replaceAt(i,"0");} else {temp = new String('000000000000000');} }
        console.log(i+" - "+temp);
        }
    }

 for(i=0;i<15;i++) 
 {
  nfu[i] = document.createElement('INPUT');
  nfu[i].type = 'checkbox';
  nfu[i].id = Math.floor((Math.random() * 100000000) + 1).toString();
  nfu[i].name = i.toString();
  nfu[i].onchange = function(e) {nfu_change(e.target,e.target.name);}
 }
}

以上将创建一个复选框输入列表,当用户选中/取消选中一个框时,相应的索引(对应于列表中的输入)将在“”中更改为“0”或“1”真/假临时“将被覆盖在cookie中。因此,在更改复选框状态时有条件地调用“nfu_change”。

1 个答案:

答案 0 :(得分:2)

我的假设是this并不代表你认为它意味着什么。通过调试器运行代码,看看this在函数执行的地方取得了什么,并且没有达到预期的效果。

编辑我认为上述假设是错误的。

我能够通过使用索引字符串调用replaceAt函数来重现您的问题。

String.prototype.replaceAt = function (index, character) {
    return this.substr(0, index) + character + this.substr(index +  character.length);
}

alert("abc".replaceAt(1, "B")); // aBc
alert("abc".replaceAt("1", "B")); //aB

以下是解决方案:

String.prototype.replaceAt = function (index, character) {
    index = parseInt(index, 10);
    return this.substr(0, index) + character + this.substr(index + character.length);
}

alert("abc".replaceAt(1, "B")); // aBc
alert("abc".replaceAt("1", "B")); //aBc
相关问题