在Javascript中使用数学的替代方案

jam*_*d69 0 javascript

我把我的Javascript代码通过分析器,并被告知不要使用with (Math).我无法找到另一种方法来使这项工作.有任何想法吗?该代码生成常规时钟和八进制时钟.我现在发布代码:

var oct = ["0", "1", "2", "3", "4", "5", "6", "7"];
var c;
var now;
var day;
var month;
var year;
var octtime;
var oct1;
var oct2;
var oct3;
var oct4;
var oct5;
var oct6;
var octvalue;
var point = ".";
function a() {
  c = checkTime;
  now = new Date();
  day = now.getDate();
  month = now.getMonth();
  year = now.getFullYear();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();
  var totsecs = hours * 3600;
  totsecs += minutes * 60;
  totsecs += seconds;
  totsecs += (now.getTime() % 1000) / 1000;
  hours = c(hours);
  minutes = c(minutes);
  seconds = c(seconds);
  with (Math) {
    octtime = floor(totsecs / (86400 / 262144))
    oct1 = floor(octtime / 32768)
    octtime -= 32768 * oct1
    oct2 = floor(octtime / 4096)
    octtime -= 4096 * oct2
    oct3 = floor(octtime / 512)
    octtime -= 512 * oct3
    oct4 = floor(octtime / 64)
    octtime -= 64 * oct4
    oct5 = floor(octtime / 8)
    octtime -= 8 * oct5
    oct6 = octtime
  }
  octvalue = point + oct[oct1] + oct[oct2] + oct[oct3] + oct[oct4] + oct[oct5] + oct[oct6]
  document.getElementById('a').innerHTML=hours+":"+minutes+":"+seconds;
  document.getElementById('b').innerHTML = octvalue
  timerID = setTimeout("a()")
  function checkTime(i)
  {
    if (i<10)
    {
      i="0" + i;
    }
    return i;
  }
}
window.onload = a;
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 5

只要前缀的所有您的来电floorMath.

更改

with (Math) {
octtime = floor(totsecs / (86400 / 262144))
Run Code Online (Sandbox Code Playgroud)

octtime = Math.floor(totsecs / (86400 / 262144))
Run Code Online (Sandbox Code Playgroud)

是的,您必须删除它们with,代码分析器是正确的.这是一种不好的做法,在严格的代码中是非法的,并且会阻止JavaScript引擎进行函数优化.请参阅MDN on.

请注意,有些细节需要在代码中进行重构.例如,当你有一个名为oct1...的变量时oct8,很可能你可以用一个数组来简化和干燥.您的变量也不应该全局变量,您可以并且应该在函数范围内定义一些变量.

如果你觉得很难处理时间格式化,那么也许你应该看看像moment.js这样的库.

当然,正确缩进的代码更易于阅读和维护......