【问题标题】:Valid output in IE9 but undefined output in IE7/IE8IE9 中的有效输出但 IE7/IE8 中的未定义输出
【发布时间】:2013-11-21 11:54:19
【问题描述】:

我编写了一个简单的“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("-"," "));


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

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


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


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

【问题讨论】:

  • 感谢所有超快速响应!我决定“接受” Saturnix 的回答,因为它是最详细的,但 Teemu 和 wiz Kid 的回答也很酷!

标签: javascript internet-explorer


【解决方案1】:

您无法在 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 的一部分。

【讨论】:

    【解决方案2】:

    IEvar temp = this.split('');) 代替 this[i]

    【讨论】:

      【解决方案3】:

      试试这个:-

      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("-"," "));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多