JavaScript,if-else速记更好的代码

时间:2019-07-12 16:19:29

标签: javascript

如何更好地编写此代码:

let styleDaysCount = {'color': 'green'}
user.demo && user.days_count < 3 ? styleDaysCount = {'color': 'red'} : styleDaysCount = {'color': 'green'}

我想删除最后一个styleDaysCount = {'color': 'green'},因为我不希望这种情况发生变化 “当用户为demo且days_count为<3时,我需要红色的样式”

我不想使用:

let styleDaysCount = {'color': 'green'}
if (user.demo && (user.days_count < 3)) { styleDaysCount = {'color': 'red'} }

5 个答案:

答案 0 :(得分:2)

您可以将条件放在对象文字中。

let styleDaysCount = {
    color: (user.demo && user.days_count < 3) ? 'red' : 'green'
}

答案 1 :(得分:0)

您也可以这样做:

const color = user.demo && user.days_count < 3 ? 'red' : 'green';
const styleDaysCount = { color };

答案 2 :(得分:0)

您只需分配三元组的结果

const styleDaysCount = user.demo && user.days_count < 3 ? {'color': 'red'} : {'color': 'green'}

答案 3 :(得分:0)

恕我直言,if / else的功能实现非常简洁明了:

实施

export const conditionally = (config) => (props) => {
  return config.if(props) ? 
    config.then(props) : config.else(props);
};

不带功能if / else的用法

function getCarConfig(car) {
  let description;
  let newPrice;

  if (car.rating > 4) {
    description = "good car";
    newPrice = car.price + 1000 * car.rating;
  } else {
    description = "bad car";
    newPrice = car.price;
  }

  return {
    description,
    newPrice,
  }
}

结合使用if / else功能

const hasGoodRating = rating => rating > 4;

const priceChange = conditionally({
  if: hasGoodRating,
  then: rating => 1000 * rating,
  else: () => 1000,
});

const getDescription = conditionally({
  if: hasGoodRating,
  then: () => "good car",
  else: () => "bad car",
});

function getCarConfig (car) {
  return {
    newPrice: priceChange(car.rating) + car.price,
    description: getDescription(car.rating)
  }
}

参考:https://itnext.io/if-else-and-try-catch-as-functional-constructs-da5c6a749f8c

答案 4 :(得分:-1)

您可以使用三元组来设置color对象的styleDaysCount

let styleDaysCount = {};
let user = {'demo': 'sunny','days_count': 6};
styleDaysCount.color = (user.demo && (user.days_count < 3)) ? 'red' : 'green';
console.log(styleDaysCount)