JavaScript,如果不是的话,速记更好的代码

JavaScript,如果不是的话,速记更好的代码,javascript,Javascript,如何更好地执行此代码: let styleDaysCount = {'color': 'green'} user.demo && user.days_count < 3 ? styleDaysCount = {'color': 'red'} : styleDaysCount = {'color': 'green'} 可以将条件放在对象文本中 let styleDaysCount = { color: (user.demo && user.days_

如何更好地执行此代码:

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

可以将条件放在对象文本中

let styleDaysCount = {
    color: (user.demo && user.days_count < 3) ? 'red' : 'green'
}
let styledaysunt={
颜色:(user.demo&&user.days\u count<3)?“红色”:“绿色”
}

您也可以这样做:

const color = user.demo && user.days_count < 3 ? 'red' : 'green';
const styleDaysCount = { color };
const color=user.demo&&user.days\u计数<3?“红色“:“绿色”;
const styledayscont={color};

您只需分配三元函数的结果即可


const styledayscont=user.demo&&user.days\u计数<3?{'color':'red'}:{'color':'green'}
IMHO 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,
  }
}
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)
  }
}
使用功能性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,
  }
}
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)
  }
}

Ref:

为什么不想使用
if
语句?尝试使用速记if-else。但我不知道现在是否有可能使用更短的代码。它被称为
三元运算
,fyiw人们为什么讨厌if语句?
const styleDaysCount={color:user.demo&&user.days\u count<3?'red':'green'}
为什么投票被否决?我不是,我只是对我觉得好的东西投了票,永远不要投票否决正确答案。有人投票否决了所有答案哈哈,甚至我的问题。。