2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 587d7b7e367417b2b2512b24
|
2020-12-16 00:37:30 -07:00
|
|
|
title: 使用三元运算符
|
2018-10-10 18:03:03 -04:00
|
|
|
challengeType: 1
|
2020-04-29 18:29:13 +08:00
|
|
|
videoUrl: 'https://scrimba.com/c/c3JRmSg'
|
|
|
|
forumTopicId: 301181
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --description--
|
|
|
|
|
2020-04-29 18:29:13 +08:00
|
|
|
条件运算符(也称为三元运算符)的用处就像写成一行的 if-else 表达式
|
2020-12-16 00:37:30 -07:00
|
|
|
|
2020-04-29 18:29:13 +08:00
|
|
|
语法如下所示:
|
2020-12-16 00:37:30 -07:00
|
|
|
|
|
|
|
`condition ? statement-if-true : statement-if-false;`
|
|
|
|
|
2020-04-29 18:29:13 +08:00
|
|
|
以下函数使用 if-else 语句来检查条件:
|
|
|
|
|
|
|
|
```js
|
|
|
|
function findGreater(a, b) {
|
|
|
|
if(a > b) {
|
|
|
|
return "a is greater";
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return "b is greater";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
上面的函数使用条件运算符写法如下:
|
|
|
|
|
|
|
|
```js
|
|
|
|
function findGreater(a, b) {
|
|
|
|
return a > b ? "a is greater" : "b is greater";
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --instructions--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
在`checkEqual`函数中使用条件运算符检查两个数字是否相等,函数应该返回 "Equal" 或 "Not Equal"
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --hints--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`checkEqual`应该使用条件运算符。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/.test(code));
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`checkEqual(1, 2)`应该返回 "Not Equal"。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(checkEqual(1, 2) === 'Not Equal');
|
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`checkEqual(1, 1)`应该返回 "Equal"。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(checkEqual(1, 1) === 'Equal');
|
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`checkEqual(1, -1)`应该返回 "Not Equal"。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(checkEqual(1, -1) === 'Not Equal');
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
2020-04-29 18:29:13 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
|
|
|
|