IE9中的有效输出,但IE7 / IE8中的未定义输出

时间:2013-11-21 11:54:19

标签: javascript internet-explorer

我写了一个简单的'replaceAll'函数,它扩展了String.prototype。

String.prototype.replaceAll = function (removalChar, insertionChar) {
    var output = "";
    for (var i = 0; i < this.length; i++) {
        if(this[i] == removalChar) {
            output += insertionChar;
        }
        else {
            output += this[i];
        }
    }
    return output;
}

测试代码:

var test = "Hello-1-2-3";
alert(test.replaceAll("-"," "));


我的测试代码会在所有浏览器中提醒Hello 1 2 3,包括IE9。

但是在IE7和8中,我得到的输出是这样的:undefinedundefinedundefinedundefinedundefinedundefined...


jsFiddle:http://jsfiddle.net/cd4Z2/ (在IE7 / IE8中试试这个)


我怎么可能重写函数以确保它在IE7 / 8上运行而不会破坏其在其他浏览器上的行为?

3 个答案:

答案 0 :(得分:3)

在IE7 / 8中,您无法使用this[i]访问字符串字符。请改用.charAt(i),如下所述:

Javascript strings - getting the char at a certain point


更新小提琴(在IE8中测试):http://jsfiddle.net/cd4Z2/2/

我刚刚用this[i]替换了this.charAt(i)


this问题中,说明了为什么您更喜欢使用charAt而不是string[index]的原因。后者不是ECMAScript 3的一部分。

答案 1 :(得分:2)

IE&lt; 9不会将字符串视为数组,即它们缺乏使用索引引用单个字母的能力。您可以使用临时数组(var temp = this.split('');)代替this[i]

答案 2 :(得分:2)

试试这个: -

String.prototype.replaceAll = function (removalChar, insertionChar) {
    var output = "";
    var res = this.split('');
    for (var i = 0; i < this.length; i++) {
        if(res[i] == removalChar) {
            output += insertionChar;
        }
        else {
            output += res[i];
        }
    }
    return output;
}


var test = "Hello-1-2-3";
//alert(test.replace("-"," "));
alert(test.replaceAll("-"," "));
相关问题