[英]Page has two scripts. One runs on all browsers. One fails on IE7.
[英]Function fails in IE7, but works in all modern browsers. How can it be fixed?
我有這個JavaScript代碼來格式化美元的數字,這個數字在Stackoverflow上得到了很多贊許。 它在最新的Web瀏覽器中運行良好,但它會導致JavaScript在IE7中失敗。 我試圖使用一個不需要JQuery的函數,因為這個項目的其余部分沒有使用它:
function formatDollar(num) {
var p = num.toFixed(2).split(".");
return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
return num + (i && !(i % 3) ? "," : "") + acc;
}, "") + "." + p[1];
}
IE7給用戶簡單地說“頁面錯誤”。 在IE7的調試模式中,抱怨它不是On Click行上提交的表單的預期Object。 如果我刪除上面的函數並讓它傳遞數字而不格式化它在IE7中工作。 它還抱怨從第一個“返回”開始的行。 我已經從JavaScript中刪除了其他所有內容,而這個功能是它出現的罪魁禍首。
reduce
函數僅在JavaScript 1.8(ECMAScript 5)及更高版本中可用,IE7沒有實現。 如果您尚未使用任何跨瀏覽器提供其功能的庫,則可以實現:
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(accumulator){
if (this===null || this===undefined) throw new TypeError("Object is null or undefined");
var i = 0, l = this.length >> 0, curr;
if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
throw new TypeError("First argument is not callable");
if(arguments.length < 2) {
if (l === 0) throw new TypeError("Array length is 0 and no second argument");
curr = this[0];
i = 1; // start accumulating at the second element
}
else
curr = arguments[1];
while (i < l) {
if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this);
++i;
}
return curr;
};
}
或者,如果您不介意不使用reduce
的簡化語法,只需在函數中使用等效循環替換它(例如上面的while
循環或for
varient)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.