2017-01-19 58 views
1

我有以下代碼來索引1處如何在不使用`var`的情況下重寫這段代碼?

const myArray = Array(1,2,3) 
 
const myOtherArray = Array(1,3,4) 
 
const myThirdArray = Array(1,5,7) 
 

 
// Creates object from array and prints it 
 
let toObject = function(x){ 
 
    var myObject 
 
    if (x[1] == 2){ 
 
    myObject = {first: x[0], 
 
     second: x[1], 
 
     third: x[2] 
 
    } 
 
    } 
 
    else if (x[1] == 3){ 
 
    myObject = {first: x[0], 
 
     second: x[1]-1, 
 
     third: x[2] 
 
    } 
 
    } 
 
    else { 
 
    myObject = {first: x[0], 
 
     second: x[1]+1, 
 
     third: x[2] 
 
    } 
 
    } 
 
    
 
    return myObject 
 
} 
 

 
console.log(toObject(myThirdArray))

與上述實現的問題返回取決於數組元素的值的不同的目的是我定義myObject並使用賦值語句。我想以「純粹功能」的方式來實現這一點,即避免可變性。在Scala或Haskell中,我想我可以使用模式匹配,但是我怎樣才能在Javascript中實現這一點?是否可以在不使用var的情況下執行此操作?

回答

5

只需在if塊中用「return」替換「myObject」即可。

只是爲了好玩,這裏是做一個完全不可讀的方式:

return { first: x[0], 
    second: (x[1]+1) - (x[1] == 2) - 2*(x[1] == 3), 
    third: x[2] 
}; 

更嚴重的是,你可能會做出「第二」一個對自己非常小的功能邏輯,並調用該函數。

但是您應該編寫兩個函數:一個用於重命名鍵,另一個用於將偏移量應用於second

+1

再加上你可以刪除'else'是完全。只保留第二個「if」。 –

+0

我不明白爲什麼技巧/噱頭的建議得到實際的代碼,而更多的「嚴重」的建議只是得到一個英文句子 – naomik

+0

@naomik,因爲它寫得很有趣,不可能解釋沒有把它放滿,它傾向於嘮叨當我必須用代碼示例翻譯「只用return替換myObject」這樣的句子時。但是如果你需要的話,它還存在於所有其他的答案中。 – djechlin

1

你在想這樣的事嗎?

let toObject = function(x){ 

    if (x[1] == 2){ 
    return {first: x[0], 
     second: x[1], 
     third: x[2] 
    }; 
    } 
    else if (x[1] == 3){ 
    return {first: x[0], 
     second: x[1]-1, 
     third: x[2] 
    }; 
    } 
    else { 
    return {first: x[0], 
     second: x[1]+1, 
     third: x[2] 
    }; 
    } 
} 
2

由於唯一的區別是第二個,你能做到這樣

let toObject = function(x){ 
    let offset = 1; 
    if (x[1] == 2){ 
     offset = 0; 
    } 
    else if (x[1] == 3){ 
     offset = -1; 
    } 

    return {first: x[0], 
     second: x[1] + offset, 
     third: x[2] 
    } 
} 
+0

正確的想法,但嵌套的三元運算符是一樣糟糕,我所做的... – djechlin

+0

你可以做出三元運算符以及..但代碼將會更長一點 –

2

我會建議代替你的函數x參數使用解構賦值。用一個簡單的switch相結合,所產生的功能提供了可讀性巨大的改善和風格

const toObject = ([first, second, third]) => { 
 
    switch (second) { 
 
    case 2: 
 
     return { first, second, third } 
 
    case 3: 
 
     return { first, second: second - 1, third } 
 
    default: 
 
     return { first, second: second + 1, third } 
 
    } 
 
} 
 

 
console.log(toObject([ 1, 2, 3 ])) 
 
// => { first: 1, second: 2, third: 3 } 
 

 
console.log(toObject([ 1, 3, 4 ])) 
 
// => { first: 1, second: 2, third: 4 } 
 

 
console.log(toObject([ 1, 5, 7 ])) 
 
// => { first: 1, second: 6, third: 7 }

+0

謝謝!這是一個非常優雅的解決方案。這更像是我正在尋找的基於模式匹配的解決方案。我不知道這在ES6中是可能的。 – nihil0

相關問題