2012-05-01 74 views
0

我在JavaScript文件中有下面這段代碼。當我運行它時,我收到錯誤消息:javascript函數可以找到另一個函數

「找不到變量:addZero」。

function addZero(n) { 
    return (n < 0 || n > 9 ? "" : "0") + n; 
} 

Date.prototype.toISODate = 
     new Function("with (this)\n return " + 
      "getFullYear()+'-'+ addZero(getMonth()+1)+ '-'" + 
      "+ addZero(getDate()) + 'T' + addZero(getHours())+':' " + 
      "+ addZero(getMinutes()) +':'+ addZero(getSeconds()) +'.000Z'"); 
+5

我不知道你打算做什麼。但**你做錯了!** – gdoron

+1

爲什麼你使用'新功能'而不是定義一個「正常」功能的任何原因? 'addZero'在全球範圍內?這段代碼的上下文是什麼? –

+0

gdoron,請問這裏有什麼不對嗎 – Amit

回答

1
function addZero(n) { 
    return (n < 0 || n > 9 ? "" : "0") + n; 
} 

Date.prototype.toISODate = function() { 
    // do what you want here 
    // with real code! not strings... 
}​ 
+0

你是否建議一些像Date.prototype.toISODate = function() { \t返回getFullYear()+' - '+ addZero(getMonth()+ 1)+' - '+ addZero(getDate())+'T'+ addZero(getHours())+':'+ addZero(getMinutes()) + ':' + addZero(getSeconds())+ '000Z'; \t } – Amit

+0

@Amit。是的,類似的東西。但是我仍然不知道你想要做什麼,如果這是做這件事的最好方法。 – gdoron

+0

感謝隊友,工作 – Amit

0

看起來你的報價是關閉。嘗試

return "with (this)\n return " + 
getFullYear() + '-' + addZero(getMonth()+1) + '-' + 
addZero(getDate()) + 'T' + addZero(getHours())+':' + 
addZero(getMinutes()) +':'+ addZero(getSeconds()) +'.000Z'; 
0

即使世界了Mozilla的JavaScript基準頁面上的良好功能產生日期ISO日期字符串

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date

/* use a function for the exact format desired... */ 
function ISODateString(d){ 
    function pad(n){return n<10 ? '0'+n : n} 
    return d.getUTCFullYear()+'-' 
     + pad(d.getUTCMonth()+1)+'-' 
     + pad(d.getUTCDate())+'T' 
     + pad(d.getUTCHours())+':' 
     + pad(d.getUTCMinutes())+':' 
     + pad(d.getUTCSeconds())+'Z' 
} 

var d = new Date(); 
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z 
0

嘗試重寫你的日期延長這個樣子,讓事情變得清晰, to avoid using the with keyword

Date.prototype.toISODate = 
    function(){ 

    function padLeft(nr,base,padStr){ 
     base = base || 10; 
     padStr = padStr || '0'; 
     var len = (String(base).length - String(nr).length)+1; 
     return len > 0? new Array(len).join(padStr)+nr : nr; 
    }  

    return [this.getFullYear(), 
      '-', 
      padLeft(this.getMonth()+1), 
      '-', 
      padLeft(this.getDate()), 
      'T', 
      padLeft(this.getHours()), 
      ':', 
      padLeft(this.getMinutes()), 
      ':', 
      padLeft(this.getSeconds()), 
      '.', 
      padLeft(this.getMilliseconds(),100), 
      'Z'].join(''); 
    }; 

The 01函數現在存在於Date.toISODate方法的範圍內。爲清楚起見,使用數組文字來構建返回字符串。使用new Function ...將功能分配給Date.prototype.toISODate這是沒有必要的,甚至可以稱爲不良做法。順便說一句,毫秒添加到結果(用零填充)。

相關問題