简体   繁体   English

如何传递单个参数而不是重复?

[英]How to pass single param instead of duplication?

How correctly refactor function, instead of duplication如何正确重构 function,而不是重复

so, now I have:所以,现在我有:

export const formatAddressLocation = (postcode, house, additions, street) => {
  let address = "";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

and
export const formatLocationInfo = (name, postcode, house, additions, street) => {
  let address = "";
  if (name) address += name + " ";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

Something like (location) = {loction.name} + formatAddressLocation(…)像 (location) = {loction.name} + formatAddressLocation(…)

Just move the name param to the end of the params, and use the second function.只需将name参数移动到params的末尾,并使用第二个function。

export const formatAddressLocation = (postcode, house, additions, street, name) => {
  let address = "";
  if (name) address += name + " ";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

You can pass params in object您可以在 object 中传递参数

your function would look like this你的 function 看起来像这样

export const formatLocationInfo = ({name, postcode, house, additions, street}) => {
  let address = "";
  if (name) address += name + " ";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

you can call your funtion like你可以像这样调用你的函数

let obj = {
   name: "",
   postcode: "",
   house: "",
   additions: "",
   street: "",
}

let address = formatLocationInfo(obj)

or或者

let address = formatLocationInfo({name: "", postcode: "", house: "",additions: "", street: ""})

You can use the following code:您可以使用以下代码:

result = `${locationName ? locationName + ' ' : ''} ${formatAddressLocation(postcode, house, additions, street)}`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM