簡體   English   中英

我該如何在沒有`var`的情況下重寫此代碼?

[英]How do I rewrite this code without the `var`?

我有以下代碼根據索引1處的數組元素的值返回不同的對象

 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來實現呢?

只需在if塊中將“ myObject”替換為“ return”即可。

只是為了好玩,這是一種完全不可讀的方法:

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

更嚴重的是,您可能會使“ second”的邏輯本身成為一個很小的函數,然后調用該函數。

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

由於只有差異是第二位,因此您可以這樣做

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

我建議使用解構賦值代替函數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 } 

您是否正在考慮這樣的事情?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM