1

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

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]
}
4

3 回答 3

1

语法节省?保存一个变量;把它放在 for 标题中

// 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;
}

但这改变了逻辑,我不确定这是想要的

也许您可以添加 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;
  }
}
于 2012-06-21T12:01:45.810 回答
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 的属性,则不需要最后三行。

于 2012-06-21T09:59:11.060 回答
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 + "];");
    }
}
于 2012-07-01T12:46:32.337 回答