【发布时间】:2011-06-16 23:44:24
【问题描述】:
我遇到了这种奇怪的情况,即类似 foreach 的 javascript 构造在 IE 中不起作用,但在 FF 中起作用。不是所有的for..in 只是这个特殊的功能不起作用。我将发布代码。在 IE8 中测试。还使用 XHTML DTD 进行了测试。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Test </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script type="text/javascript">
<!--
String.prototype.format = function() {
var formatted = this;
var mycars = new Array(); //some
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
var arg;
for (arg in mycars) { alert('it comes here');
formatted = formatted.replace("{" + arg + "}", arguments[arg]); }
return formatted;
};
String.prototype.format2 = function() {
var formatted = this;
var arg;
for (arg in arguments) { alert('it does not come here');
formatted = formatted.replace("{" + arg + "}", arguments[arg]); }
return formatted;
};
function fn() {
var s = 'The {0} is dead. Don\'t code {0}. Code {1} that is open source!'.format('ASP', 'PHP');
alert('format:'+s);
var s2 = 'The {0} is dead. Don\'t code {0}. Code {1} that is open source!'.format2('ASP', 'PHP');
alert('format2:'+s2); //does not replace {0}s and {1}s
}
//-->
</script>
<BODY>
<input type="button" value="click " onclick="fn();" />
</BODY>
</HTML>
更新我发布了一个错误的问题,它在 FireFox 中有效,但在 IE8 中无效,这是错误的。它也不适用于 FireFox。实际上,我是从JavaScript equivalent to printf/string.format 帖子中获得此代码的。
【问题讨论】:
-
你用的是哪个版本的IE?
-
我使用的是 IE8、FF3.6.8 和 chrome 8.0.552
标签: javascript internet-explorer foreach arguments