2012-06-21 57 views
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] 
} 
+0

如果你試圖解釋你想達到什麼,那麼給你一個解決方案會更容易。 – jishi

+0

這段代碼真的可以做任何事情,只要'format [i]'的位置中的字符串匹配''m'',''d就將'm','d'或'y'賦值給'date [i] 「'或'」y「'分別。 – elclanrs

回答

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

語法保存? 保存一個var;把它放在了頭

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

但是,這改變了邏輯和IM不知道這是想

也許你可以添加一個繼續執行速度更快,但再次不確定邏輯

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; 
    } 
} 
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 + "];"); 
    } 
}