有没有办法写这个更短/干燥?

时间:2012-06-21 08:04:25

标签: javascript dry

只是想知道是否还有我可以写这个循环更短。

var m, d, y

// date.length === format.length
for (var i = 0, len = format.length; i < len; i++) {
  if (/m/.test(format[i])) m = date[i]
  if (/d/.test(format[i])) d = date[i]
  if (/y/.test(format[i])) y = date[i]
}

3 个答案:

答案 0 :(得分:1)

你的例子很短,所以我不会改变它,但为了一个例子,你可以使你的代码更加动态:

var obj = {};
var mdy = ['m', 'd', 'y']
var curLetter;
for (var i = 0, len = format.length; i < len; i++) {
    curLetter = mdy[i];
    if ((new Regexp(curLetter)).test(format[i])) obj[curLetter] = date[i];
}
var m = obj.m;
var d = obj.d;
var y = obj.y;

你不需要的最后三行,如果你只是obj的属性。

答案 1 :(得分:1)

语法保存? 保存变量;把它放在for header

// date.length === format.length
for (var m, d, y, i = 0, len = format.length; i < len; i++) {
  if (/m/.test(format[i])) m = date[i]
  if (/d/.test(format[i])) d = date[i]
  if (/y/.test(format[i])) y = date[i]
}

或者条件:

for (var m, d, y, i = 0, len = format.length; i < len; i++) {
  (/m/.test(format[i])) ? m = date[i] 
  :(/d/.test(format[i])) ? d = date[i] 
  :(/y/.test(format[i])) y = date[i] 
  : continue;
}

但这改变了逻辑,我不确定这是否需要

也许你可以添加一个继续以加快执行速度但又不确定逻辑

for (var m, d, y, i = 0, len = format.length; i < len; i++) {
  if (/m/.test(format[i])){
    m = date[i]
    //jump to next since this has been found
    continue;
  }
  if (/d/.test(format[i])){
    d = date[i]
    continue;
  }
  if (/y/.test(format[i])){
    y = date[i]
    continue;
  }
}

答案 2 :(得分:1)

您可以使用eval()编写更通用的循环。

var parts = ['d', 'm', 'y'],
    part,
    indexOfPart,
    d, m, y;

// Iterate over the variable you want to assign
for (int i = 0; i < parts.length; i++) {
    part = parts[i];

    // Find out where in the format is the current part of the date
    indexOfPart = format.indexOf(part);

    // If it is present, use eval to assign your variable
    if (indexOfPart !== -1) {
        eval(part + " = date[" + indexOfPart + "];");
    }
}