Разъяснение о том, если заявления - PullRequest
1 голос
/ 19 мая 2019

Получил этот код:

function orderMyLogic(val) {
  if (val < 10) {
    return "Less than 10";
  } else if (val < 5) {
    return "Less than 5";
  } else {
    return "Greater than or equal to 10";
  }
}


console.log(orderMyLogic(7));
console.log(orderMyLogic(4));
console.log(orderMyLogic(11));

Итак, результат

Less than 10
Less than 10
Greater than or equal to 10

Я понимаю, почему это результат, но какие варианты в синтаксисе (если есть) что я могу взять, так что их результат будет таким же, как в коде ниже без изменения мест (val <10) и (val <5) </p>

function orderMyLogic(val) {
  if (val < 5) {
    return "Less than 5";
  } else if (val < 10) {
    return "Less than 10";
  } else {
    return "Greater than or equal to 10";
  }
}

console.log(orderMyLogic(7));
console.log(orderMyLogic(4));
console.log(orderMyLogic(11));

что результат будет:

Less than 10
Less than 5
Greater than or equal to 10

1 Ответ

1 голос
/ 19 мая 2019

Для решения без оператора if можно использовать условный (троичный) оператор ?: со значениями.

function orderMyLogic(val) {
    return val < 5
        ? "Less than 5"
        : val < 10
            ? "Less than 10"
            : "Greater than or equal to 10";
}

console.log(orderMyLogic(7));
console.log(orderMyLogic(4));
console.log(orderMyLogic(11));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...