IE9中的有效输出,但IE7/IE8中的未定义输出
Valid output in IE9 but undefined output in IE7/IE8
我写了一个简单的"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和IE8中,我得到的输出是这样的:undefinedundefinedundefinedundefinedundefinedundefined...
jsFiddle:http://jsfiddle.net/cd4Z2/(在IE7/IE8中尝试此操作)
我怎么可能重写这个函数,以确保它在IE7/8上运行,而不破坏它在其他浏览器上的行为?
在IE7/8中,不能使用this[i]
访问字符串字符。使用.charAt(i)
,如下所述:
Javascript字符串-在某个点获取字符
更新的fiddle(在IE8中测试):http://jsfiddle.net/cd4Z2/2/
我刚刚用this.charAt(i)
替换了this[i]
。
在这个问题中,有一些很好的理由说明了为什么您更喜欢使用charAt
而不是string[index]
。后者不是ECMAScript 3的一部分。
IE<9并不像数组那样对待字符串,也就是说,它们缺乏用索引引用单个字母的能力。您可以使用临时数组(var temp = this.split('');
)而不是this[i]
试试这个:-
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("-"," "));
相关文章:
- Recaptcha在IE7和IE8中不起作用
- 在JavaScript中输出转义字符
- 如何在jQuery中将函数的输出分配给变量
- Javascript,输出结果后页面不断刷新
- Joomla Gantry Framework ie8 LESS/CSS
- 为什么jQuery 1.8不能在IE8和InternetExplorer9中使用?(截至2012年9月的IE9最新版本)
- 在IE8中不起作用的元素上触发单击事件
- Datetime格式为Friendly Time.Moment JS输出错误
- 如何将angularjs中的javascript字符串输出为循环数组
- 谷歌地图v3标记没有显示ie8和9
- HTML5FileReader输出到D3.js图表
- console.log以外的Javascript输出函数
- Eloquent JavaScript递归示例如何终止为返回1,但仍然输出指数值
- PHP中的数组输出
- 以不同的顺序输出数据
- 使用Rivets.js输出类
- 在Chrome扩展内部输出Google API调用
- 数据-在IE8中不起作用
- IE9中的有效输出,但IE7/IE8中的未定义输出
- jQuery AJAX和IE8输出“;无效的参数"