chore: seed chinese traditional (#42005)
Seeds the chinese traditional files manually so we can deploy to staging.
This commit is contained in:
committed by
GitHub
parent
e46e80e08f
commit
3da4be21bb
@ -0,0 +1,97 @@
|
||||
---
|
||||
id: a77dbc43c33f39daa4429b4f
|
||||
title: 基本類型布爾值的檢查
|
||||
challengeType: 5
|
||||
forumTopicId: 16000
|
||||
dashedName: boo-who
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
檢查一個值是否是基本類型中的布爾值(boolean)類型。 函數應返回 `true` 或者 `false`。
|
||||
|
||||
基本類型中的布爾值爲 `true` 或者 `false`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`booWho(true)` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(true), true);
|
||||
```
|
||||
|
||||
`booWho(false)` 應該返回 `true`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(false), true);
|
||||
```
|
||||
|
||||
`booWho([1, 2, 3])` 應該返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho([1, 2, 3]), false);
|
||||
```
|
||||
|
||||
`booWho([].slice)` 應該返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho([].slice), false);
|
||||
```
|
||||
|
||||
`booWho({ "a": 1 })` 應該返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho({ a: 1 }), false);
|
||||
```
|
||||
|
||||
`booWho(1)` 應該返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(1), false);
|
||||
```
|
||||
|
||||
`booWho(NaN)` 應該返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(NaN), false);
|
||||
```
|
||||
|
||||
`booWho("a")` 應該返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('a'), false);
|
||||
```
|
||||
|
||||
`booWho("true")` 應該返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('true'), false);
|
||||
```
|
||||
|
||||
`booWho("false")` 應該返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('false'), false);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function booWho(bool) {
|
||||
return bool;
|
||||
}
|
||||
|
||||
booWho(null);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function booWho(bool) {
|
||||
return typeof bool === "boolean";
|
||||
}
|
||||
|
||||
booWho(null);
|
||||
```
|
@ -0,0 +1,110 @@
|
||||
---
|
||||
id: a9bd25c716030ec90084d8a1
|
||||
title: 分割數組
|
||||
challengeType: 5
|
||||
forumTopicId: 16005
|
||||
dashedName: chunky-monkey
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
請編寫一個函數,該函數將一個數組(第一個參數)拆分成若干長度爲 `size`(第二個參數)的子數組,並將它們作爲二維數組返回。
|
||||
|
||||
# --hints--
|
||||
|
||||
`chunkArrayInGroups(["a", "b", "c", "d"], 2)` 應返回 `[["a", "b"], ["c", "d"]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [
|
||||
['a', 'b'],
|
||||
['c', 'd']
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)` 應返回 `[[0, 1, 2], [3, 4, 5]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [
|
||||
[0, 1, 2],
|
||||
[3, 4, 5]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)` 應返回 `[[0, 1], [2, 3], [4, 5]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [
|
||||
[0, 1],
|
||||
[2, 3],
|
||||
[4, 5]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)` 應返回 `[[0, 1, 2, 3], [4, 5]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [
|
||||
[0, 1, 2, 3],
|
||||
[4, 5]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)` 應返回 `[[0, 1, 2], [3, 4, 5], [6]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [
|
||||
[0, 1, 2],
|
||||
[3, 4, 5],
|
||||
[6]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` 應返回 `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [
|
||||
[0, 1, 2, 3],
|
||||
[4, 5, 6, 7],
|
||||
[8]
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)` 應返回 `[[0, 1], [2, 3], [4, 5], [6, 7], [8]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [
|
||||
[0, 1],
|
||||
[2, 3],
|
||||
[4, 5],
|
||||
[6, 7],
|
||||
[8]
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function chunkArrayInGroups(arr, size) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
chunkArrayInGroups(["a", "b", "c", "d"], 2);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function chunkArrayInGroups(arr, size) {
|
||||
let out = [];
|
||||
|
||||
for (let i = 0; i < arr.length; i += size) {
|
||||
out.push(arr.slice(i, i + size));
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
chunkArrayInGroups(["a", "b", "c", "d"], 2);
|
||||
```
|
@ -0,0 +1,113 @@
|
||||
---
|
||||
id: acda2fb1324d9b0fa741e6b5
|
||||
title: 確認結尾
|
||||
challengeType: 5
|
||||
forumTopicId: 16006
|
||||
dashedName: confirm-the-ending
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
檢查字符串(第一個參數 `str`)是否以給定的目標字符串(第二個參數 `target`)結束。
|
||||
|
||||
這個挑戰 *可以* 用 ES2015 引入的 `.endsWith()` 方法來解決。但在這個挑戰中,請使用 JavaScript 的字符串子串方法。
|
||||
|
||||
# --hints--
|
||||
|
||||
`confirmEnding("Bastian", "n")` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Bastian', 'n') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Congratulation", "on")` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Congratulation', 'on') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Connor", "n")` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Connor', 'n') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
confirmEnding(
|
||||
'Walking on water and developing software from a specification are easy if both are frozen',
|
||||
'specification'
|
||||
) === false
|
||||
);
|
||||
```
|
||||
|
||||
`confirmEnding("He has to give me a new name", "name")` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(confirmEnding('He has to give me a new name', 'name') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "same")` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'same') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "sage")` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'sage') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "game")` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'game') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
confirmEnding(
|
||||
'If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing',
|
||||
'mountain'
|
||||
) === false
|
||||
);
|
||||
```
|
||||
|
||||
`confirmEnding("Abstraction", "action")` 應該返回 `true`。
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Abstraction', 'action') === true);
|
||||
```
|
||||
|
||||
不應使用內置方法 `.endsWith()` 來完成挑戰。
|
||||
|
||||
```js
|
||||
assert(!/\.endsWith\(.*?\)\s*?;?/.test(code) && !/\['endsWith'\]/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function confirmEnding(str, target) {
|
||||
return str;
|
||||
}
|
||||
|
||||
confirmEnding("Bastian", "n");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function confirmEnding(str, target) {
|
||||
return str.substring(str.length - target.length) === target;
|
||||
}
|
||||
|
||||
confirmEnding("Bastian", "n");
|
||||
```
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b3
|
||||
title: 將攝氏度轉換爲華氏度
|
||||
challengeType: 1
|
||||
forumTopicId: 16806
|
||||
dashedName: convert-celsius-to-fahrenheit
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
將攝氏度轉換爲華氏度的計算方式爲:攝氏度乘以 `9/5` 然後加上 `32`。
|
||||
|
||||
輸入參數 `celsius` 代表一個攝氏度的溫度。 使用已定義的變量 `fahrenheit`,並賦值爲相應的華氏度的溫度值。 根據上述轉換公式來進行轉換。
|
||||
|
||||
# --hints--
|
||||
|
||||
`convertToF(0)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof convertToF(0) === 'number');
|
||||
```
|
||||
|
||||
`convertToF(-30)` 應返回 `-22`。
|
||||
|
||||
```js
|
||||
assert(convertToF(-30) === -22);
|
||||
```
|
||||
|
||||
`convertToF(-10)` 應返回 `14`。
|
||||
|
||||
```js
|
||||
assert(convertToF(-10) === 14);
|
||||
```
|
||||
|
||||
`convertToF(0)` 應返回 `32`。
|
||||
|
||||
```js
|
||||
assert(convertToF(0) === 32);
|
||||
```
|
||||
|
||||
`convertToF(20)` 應返回 `68`。
|
||||
|
||||
```js
|
||||
assert(convertToF(20) === 68);
|
||||
```
|
||||
|
||||
`convertToF(30)` 應返回 `86`。
|
||||
|
||||
```js
|
||||
assert(convertToF(30) === 86);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function convertToF(celsius) {
|
||||
let fahrenheit;
|
||||
return fahrenheit;
|
||||
}
|
||||
|
||||
convertToF(30);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function convertToF(celsius) {
|
||||
let fahrenheit = celsius * 9/5 + 32;
|
||||
|
||||
return fahrenheit;
|
||||
}
|
||||
|
||||
convertToF(30);
|
||||
```
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: a302f7aae1aa3152a5b413bc
|
||||
title: 計算整數的階乘
|
||||
challengeType: 5
|
||||
forumTopicId: 16013
|
||||
dashedName: factorialize-a-number
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
返回一個給定整數的階乘計算結果。
|
||||
|
||||
對於整數 `n`,n 的階乘就是所有小於等於 `n` 的正整數的乘積。
|
||||
|
||||
階乘通常用符號 `n!` 來表示。
|
||||
|
||||
例如:`5! = 1 * 2 * 3 * 4 * 5 = 120`
|
||||
|
||||
在這個挑戰中,只有非負整數會作爲參數傳入函數。
|
||||
|
||||
# --hints--
|
||||
|
||||
`factorialize(5)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof factorialize(5) === 'number');
|
||||
```
|
||||
|
||||
`factorialize(5)` 應該返回 `120`。
|
||||
|
||||
```js
|
||||
assert(factorialize(5) === 120);
|
||||
```
|
||||
|
||||
`factorialize(10)` 應該返回 `3628800`。
|
||||
|
||||
```js
|
||||
assert(factorialize(10) === 3628800);
|
||||
```
|
||||
|
||||
`factorialize(20)` 應該返回 `2432902008176640000`。
|
||||
|
||||
```js
|
||||
assert(factorialize(20) === 2432902008176640000);
|
||||
```
|
||||
|
||||
`factorialize(0)` 應該返回 `1`。
|
||||
|
||||
```js
|
||||
assert(factorialize(0) === 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function factorialize(num) {
|
||||
return num;
|
||||
}
|
||||
|
||||
factorialize(5);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function factorialize(num) {
|
||||
return num < 1 ? 1 : num * factorialize(num - 1);
|
||||
}
|
||||
|
||||
factorialize(5);
|
||||
```
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: adf08ec01beb4f99fc7a68f2
|
||||
title: 過濾數組中的假值
|
||||
challengeType: 5
|
||||
forumTopicId: 16014
|
||||
dashedName: falsy-bouncer
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
從數組中移除所有假值(falsy values)。
|
||||
|
||||
JavaScript 中的假值有 `false`、`null`、`0`、`""`、`undefined`、`NaN`。
|
||||
|
||||
提示:可以考慮將每個值都轉換爲布爾值(boolean)。
|
||||
|
||||
# --hints--
|
||||
|
||||
`bouncer([7, "ate", "", false, 9])` 應返回 `[7, "ate", 9]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([7, 'ate', '', false, 9]), [7, 'ate', 9]);
|
||||
```
|
||||
|
||||
`bouncer(["a", "b", "c"])` 應返回 `["a", "b", "c"]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer(['a', 'b', 'c']), ['a', 'b', 'c']);
|
||||
```
|
||||
|
||||
`bouncer([false, null, 0, NaN, undefined, ""])` 應返回 `[]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([false, null, 0, NaN, undefined, '']), []);
|
||||
```
|
||||
|
||||
`bouncer([null, NaN, 1, 2, undefined])` 應返回 `[1, 2]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([null, NaN, 1, 2, undefined]), [1, 2]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function bouncer(arr) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
bouncer([7, "ate", "", false, 9]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function bouncer(arr) {
|
||||
return arr.filter(e => e);
|
||||
}
|
||||
|
||||
bouncer([7, "ate", "", false, 9]);
|
||||
```
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: a26cbbe9ad8655a977e1ceb5
|
||||
title: 找出字符串中的最長單詞
|
||||
challengeType: 5
|
||||
forumTopicId: 16015
|
||||
dashedName: find-the-longest-word-in-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
返回給出的句子中,最長單詞的長度。
|
||||
|
||||
函數的返回值應是一個數字。
|
||||
|
||||
# --hints--
|
||||
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(
|
||||
typeof findLongestWordLength(
|
||||
'The quick brown fox jumped over the lazy dog'
|
||||
) === 'number'
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` 應返回 `6`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
findLongestWordLength('The quick brown fox jumped over the lazy dog') === 6
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("May the force be with you")` 應返回 `5`。
|
||||
|
||||
```js
|
||||
assert(findLongestWordLength('May the force be with you') === 5);
|
||||
```
|
||||
|
||||
`findLongestWordLength("Google do a barrel roll")` 應返回 `6`。
|
||||
|
||||
```js
|
||||
assert(findLongestWordLength('Google do a barrel roll') === 6);
|
||||
```
|
||||
|
||||
`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` 應返回 `8`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
findLongestWordLength(
|
||||
'What is the average airspeed velocity of an unladen swallow'
|
||||
) === 8
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` 應返回 `19`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
findLongestWordLength(
|
||||
'What if we try a super-long word such as otorhinolaryngology'
|
||||
) === 19
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findLongestWordLength(str) {
|
||||
return str.length;
|
||||
}
|
||||
|
||||
findLongestWordLength("The quick brown fox jumped over the lazy dog");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findLongestWordLength(str) {
|
||||
return str.split(' ').sort((a, b) => b.length - a.length)[0].length;
|
||||
}
|
||||
|
||||
findLongestWordLength("The quick brown fox jumped over the lazy dog");
|
||||
```
|
@ -0,0 +1,58 @@
|
||||
---
|
||||
id: a6e40f1041b06c996f7b2406
|
||||
title: 按參數過濾數組
|
||||
challengeType: 5
|
||||
forumTopicId: 16016
|
||||
dashedName: finders-keepers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
請寫一個函數來檢查數組(第一個參數 `arr`)中的元素,並返回數組中第一個通過校驗測試的元素。 其中,“通過校驗測試”指的是對於數組中的一個元素 `x`,若 `func(x)` 返回的結果爲 `true`,則校驗測試通過。 如果沒有元素通過測試,請返回 `undefined`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` 應返回 `8`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
findElement([1, 3, 5, 8, 9, 10], function (num) {
|
||||
return num % 2 === 0;
|
||||
}),
|
||||
8
|
||||
);
|
||||
```
|
||||
|
||||
`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` 應返回 `undefined`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
findElement([1, 3, 5, 9], function (num) {
|
||||
return num % 2 === 0;
|
||||
}),
|
||||
undefined
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findElement(arr, func) {
|
||||
let num = 0;
|
||||
return num;
|
||||
}
|
||||
|
||||
findElement([1, 2, 3, 4], num => num % 2 === 0);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findElement(arr, func) {
|
||||
return arr.filter(func)[0];
|
||||
}
|
||||
|
||||
findElement([1, 2, 3, 4], num => num % 2 === 0);
|
||||
```
|
@ -0,0 +1,117 @@
|
||||
---
|
||||
id: af2170cad53daa0770fabdea
|
||||
title: 比較字符串
|
||||
challengeType: 5
|
||||
forumTopicId: 16025
|
||||
dashedName: mutations
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
如果數組裏的第一個字符串包含了第二個字符串中的所有字母,則返回 `true`。
|
||||
|
||||
例如,`["hello", "Hello"]` 應該返回 `true`。因爲在忽略大小寫的情況下,第一個字符串包含了第二個字符串裏出現的所有字母。
|
||||
|
||||
`["hello", "hey"]` 應該返回 `false`。因爲 `hello` 並不包含字符 `y`。
|
||||
|
||||
最後,`["Alien", "line"]` 應該返回 `true`。因爲 `line` 中的所有字母都出現在了 `Alien` 中。
|
||||
|
||||
# --hints--
|
||||
|
||||
`mutation(["hello", "hey"])` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'hey']) === false);
|
||||
```
|
||||
|
||||
`mutation(["hello", "Hello"])` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'Hello']) === true);
|
||||
```
|
||||
|
||||
`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(mutation(['zyxwvutsrqponmlkjihgfedcba', 'qrstu']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Mary", "Army"])` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(mutation(['Mary', 'Army']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Mary", "Aarmy"])` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(mutation(['Mary', 'Aarmy']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Alien", "line"])` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(mutation(['Alien', 'line']) === true);
|
||||
```
|
||||
|
||||
`mutation(["floor", "for"])` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(mutation(['floor', 'for']) === true);
|
||||
```
|
||||
|
||||
`mutation(["hello", "neo"])` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'neo']) === false);
|
||||
```
|
||||
|
||||
`mutation(["voodoo", "no"])` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(mutation(['voodoo', 'no']) === false);
|
||||
```
|
||||
|
||||
`mutation(["ate", "date"])` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(mutation(['ate', 'date']) === false);
|
||||
```
|
||||
|
||||
`mutation(["Tiger", "Zebra"])` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(mutation(['Tiger', 'Zebra']) === false);
|
||||
```
|
||||
|
||||
`mutation(["Noel", "Ole"])` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(mutation(['Noel', 'Ole']) === true);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function mutation(arr) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
mutation(["hello", "hey"]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function mutation(arr) {
|
||||
let hash = Object.create(null);
|
||||
|
||||
arr[0].toLowerCase().split('').forEach(c => hash[c] = true);
|
||||
|
||||
return !arr[1].toLowerCase().split('').filter(c => !hash[c]).length;
|
||||
}
|
||||
|
||||
mutation(["hello", "hey"]);
|
||||
```
|
@ -0,0 +1,84 @@
|
||||
---
|
||||
id: afcc8d540bea9ea2669306b6
|
||||
title: 重複輸出字符串
|
||||
challengeType: 5
|
||||
forumTopicId: 16041
|
||||
dashedName: repeat-a-string-repeat-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
將一個給定的字符串 `str`(第一個參數)重複輸出 `num`(第二個參數)次。 如果 `num` 不是正數,返回空字符串。 在這個挑戰中,請*不要*使用 JavaScript 內置的 `.repeat()` 方法。
|
||||
|
||||
# --hints--
|
||||
|
||||
`repeatStringNumTimes("*", 3)` 應返回 `***`。
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('*', 3) === '***');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 3)` 應返回 `abcabcabc`。
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 3) === 'abcabcabc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 4)` 應返回 `abcabcabcabc`。
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 4) === 'abcabcabcabc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 1)` 應返回 `abc`。
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 1) === 'abc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("*", 8)` 應返回 `********`。
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('*', 8) === '********');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", -2)` 應返回 `""`。
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', -2) === '');
|
||||
```
|
||||
|
||||
不應使用內置的 `repeat()` 方法。
|
||||
|
||||
```js
|
||||
assert(!/\.repeat/g.test(code));
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 0)` 應返回 `""`。
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 0) === '');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function repeatStringNumTimes(str, num) {
|
||||
return str;
|
||||
}
|
||||
|
||||
repeatStringNumTimes("abc", 3);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function repeatStringNumTimes(str, num) {
|
||||
if (num < 1) return '';
|
||||
return num === 1 ? str : str + repeatStringNumTimes(str, num-1);
|
||||
}
|
||||
|
||||
repeatStringNumTimes("abc", 3);
|
||||
```
|
@ -0,0 +1,92 @@
|
||||
---
|
||||
id: a789b3483989747d63b0e427
|
||||
title: 找出多個數組中的最大數字
|
||||
challengeType: 5
|
||||
forumTopicId: 16042
|
||||
dashedName: return-largest-numbers-in-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
請返回一個數組,該數組由參數中每個子數組中的最大數字組成。 爲簡單起見,給出的數組總會包含 4 個子數組。
|
||||
|
||||
別忘了,你可以通過 for 循環遍歷一個數組,並用 `arr[i]` 的寫法來訪問數組中的元素。
|
||||
|
||||
# --hints--
|
||||
|
||||
`largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])` 應返回一個數組。
|
||||
|
||||
```js
|
||||
assert(
|
||||
largestOfFour([
|
||||
[4, 5, 1, 3],
|
||||
[13, 27, 18, 26],
|
||||
[32, 35, 37, 39],
|
||||
[1000, 1001, 857, 1]
|
||||
]).constructor === Array
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])` 應返回 `[27, 5, 39, 1001]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
largestOfFour([
|
||||
[13, 27, 18, 26],
|
||||
[4, 5, 1, 3],
|
||||
[32, 35, 37, 39],
|
||||
[1000, 1001, 857, 1]
|
||||
]),
|
||||
[27, 5, 39, 1001]
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])` 應返回 `[9, 35, 97, 1000000]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
largestOfFour([
|
||||
[4, 9, 1, 3],
|
||||
[13, 35, 18, 26],
|
||||
[32, 35, 97, 39],
|
||||
[1000000, 1001, 857, 1]
|
||||
]),
|
||||
[9, 35, 97, 1000000]
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])` 應返回 `[25, 48, 21, -3]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
largestOfFour([
|
||||
[17, 23, 25, 12],
|
||||
[25, 7, 34, 48],
|
||||
[4, -10, 18, 21],
|
||||
[-72, -3, -17, -10]
|
||||
]),
|
||||
[25, 48, 21, -3]
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function largestOfFour(arr) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function largestOfFour(arr) {
|
||||
return arr.map(subArr => Math.max.apply(null, subArr));
|
||||
}
|
||||
|
||||
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
|
||||
```
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: a202eed8fc186c8434cb6d61
|
||||
title: 反轉字符串
|
||||
challengeType: 5
|
||||
forumTopicId: 16043
|
||||
dashedName: reverse-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
請反轉傳入函數的字符串。
|
||||
|
||||
在反轉字符串之前,你可能需要將其切分成包含字符的數組。
|
||||
|
||||
函數的返回結果應爲字符串。
|
||||
|
||||
# --hints--
|
||||
|
||||
`reverseString("hello")` 應返回一個字符串。
|
||||
|
||||
```js
|
||||
assert(typeof reverseString('hello') === 'string');
|
||||
```
|
||||
|
||||
`reverseString("hello")` 應返回 `olleh`。
|
||||
|
||||
```js
|
||||
assert(reverseString('hello') === 'olleh');
|
||||
```
|
||||
|
||||
`reverseString("Howdy")` 應返回 `ydwoH`。
|
||||
|
||||
```js
|
||||
assert(reverseString('Howdy') === 'ydwoH');
|
||||
```
|
||||
|
||||
`reverseString("Greetings from Earth")` 應返回 `htraE morf sgniteerG`。
|
||||
|
||||
```js
|
||||
assert(reverseString('Greetings from Earth') === 'htraE morf sgniteerG');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function reverseString(str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
reverseString("hello");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function reverseString(str) {
|
||||
return str.split('').reverse().join('');
|
||||
}
|
||||
|
||||
reverseString("hello");
|
||||
```
|
@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 579e2a2c335b9d72dd32e05c
|
||||
title: Slice 與 Splice
|
||||
challengeType: 5
|
||||
forumTopicId: 301148
|
||||
dashedName: slice-and-splice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
本挑戰的輸入參數爲兩個數組和一個索引值。
|
||||
|
||||
將第一個數組中的所有元素依次複製到第二個數組中。
|
||||
|
||||
請注意,你需要從第二個數組索引值爲 `n` 的地方開始插入。
|
||||
|
||||
最後,請返回插入元素後的數組。 作爲輸入參數的兩個數組在函數執行前後應保持不變。
|
||||
|
||||
# --hints--
|
||||
|
||||
`frankenSplice([1, 2, 3], [4, 5], 1)` 應返回 `[4, 1, 2, 3, 5]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice([1, 2, 3], [4, 5], 1), [4, 1, 2, 3, 5]);
|
||||
```
|
||||
|
||||
`frankenSplice([1, 2], ["a", "b"], 1)` 應返回 `["a", 1, 2, "b"]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice(testArr1, testArr2, 1), ['a', 1, 2, 'b']);
|
||||
```
|
||||
|
||||
`frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)` 應返回 `["head", "shoulders", "claw", "tentacle", "knees", "toes"]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
frankenSplice(
|
||||
['claw', 'tentacle'],
|
||||
['head', 'shoulders', 'knees', 'toes'],
|
||||
2
|
||||
),
|
||||
['head', 'shoulders', 'claw', 'tentacle', 'knees', 'toes']
|
||||
);
|
||||
```
|
||||
|
||||
第一個數組中的所有元素都應按原始順序添加到第二個數組中。
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice([1, 2, 3, 4], [], 0), [1, 2, 3, 4]);
|
||||
```
|
||||
|
||||
函數運行後,第一個數組應保持不變。
|
||||
|
||||
```js
|
||||
frankenSplice(testArr1, testArr2, 1);
|
||||
assert.deepEqual(testArr1, [1, 2]);
|
||||
```
|
||||
|
||||
函數運行後,第二個數組應保持不變。
|
||||
|
||||
```js
|
||||
frankenSplice(testArr1, testArr2, 1);
|
||||
assert.deepEqual(testArr2, ['a', 'b']);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
let testArr1 = [1, 2];
|
||||
let testArr2 = ["a", "b"];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function frankenSplice(arr1, arr2, n) {
|
||||
return arr2;
|
||||
}
|
||||
|
||||
frankenSplice([1, 2, 3], [4, 5, 6], 1);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function frankenSplice(arr1, arr2, n) {
|
||||
// It's alive. It's alive!
|
||||
let result = arr2.slice();
|
||||
for (let i = 0; i < arr1.length; i++) {
|
||||
result.splice(n+i, 0, arr1[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
frankenSplice([1, 2, 3], [4, 5], 1);
|
||||
```
|
@ -0,0 +1,64 @@
|
||||
---
|
||||
id: ab6137d4e35944e21037b769
|
||||
title: 句中單詞首字母大寫
|
||||
challengeType: 5
|
||||
forumTopicId: 16088
|
||||
dashedName: title-case-a-sentence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
請將傳入的字符串中,每個單詞的第一個字母變成大寫並返回。 注意除首字母外,其餘的字符都應是小寫的。
|
||||
|
||||
在這個挑戰中,我們還需要將諸如 `the` 和 `of` 之類的連接詞大寫。
|
||||
|
||||
# --hints--
|
||||
|
||||
`titleCase("I'm a little tea pot")` 應返回一個字符串。
|
||||
|
||||
```js
|
||||
assert(typeof titleCase("I'm a little tea pot") === 'string');
|
||||
```
|
||||
|
||||
`titleCase("I'm a little tea pot")` 應返回 `I'm A Little Tea Pot`。
|
||||
|
||||
```js
|
||||
assert(titleCase("I'm a little tea pot") === "I'm A Little Tea Pot");
|
||||
```
|
||||
|
||||
`titleCase("sHoRt AnD sToUt")` 應返回 `Short And Stout`。
|
||||
|
||||
```js
|
||||
assert(titleCase('sHoRt AnD sToUt') === 'Short And Stout');
|
||||
```
|
||||
|
||||
`titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` 應返回 `Here Is My Handle Here Is My Spout`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
titleCase('HERE IS MY HANDLE HERE IS MY SPOUT') ===
|
||||
'Here Is My Handle Here Is My Spout'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function titleCase(str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
titleCase("I'm a little tea pot");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function titleCase(str) {
|
||||
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1).toLowerCase()).join(' ');
|
||||
}
|
||||
|
||||
titleCase("I'm a little tea pot");
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: ac6993d51946422351508a41
|
||||
title: 截斷字符串
|
||||
challengeType: 5
|
||||
forumTopicId: 16089
|
||||
dashedName: truncate-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
如果傳入的字符串(第一個參數)的長度大於傳入的值(第二個參數),請在這個位置截斷它, 並在後面加上 `...`,然後返回結果。
|
||||
|
||||
# --hints--
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", 8)` 應返回 `A-tisket...`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
truncateString('A-tisket a-tasket A green and yellow basket', 8) ===
|
||||
'A-tisket...'
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("Peter Piper picked a peck of pickled peppers", 11)` 應返回 `Peter Piper...`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
truncateString('Peter Piper picked a peck of pickled peppers', 11) ===
|
||||
'Peter Piper...'
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)` 應返回 `A-tisket a-tasket A green and yellow basket`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
truncateString(
|
||||
'A-tisket a-tasket A green and yellow basket',
|
||||
'A-tisket a-tasket A green and yellow basket'.length
|
||||
) === 'A-tisket a-tasket A green and yellow basket'
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)` 應返回 `A-tisket a-tasket A green and yellow basket`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
truncateString(
|
||||
'A-tisket a-tasket A green and yellow basket',
|
||||
'A-tisket a-tasket A green and yellow basket'.length + 2
|
||||
) === 'A-tisket a-tasket A green and yellow basket'
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-", 1)` 應返回字符串 `A...`。
|
||||
|
||||
```js
|
||||
assert(truncateString('A-', 1) === 'A...');
|
||||
```
|
||||
|
||||
`truncateString("Absolutely Longer", 2)` 應返回 `Ab...`。
|
||||
|
||||
```js
|
||||
assert(truncateString('Absolutely Longer', 2) === 'Ab...');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function truncateString(str, num) {
|
||||
return str;
|
||||
}
|
||||
|
||||
truncateString("A-tisket a-tasket A green and yellow basket", 8);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function truncateString(str, num) {
|
||||
if (num >= str.length) {
|
||||
return str;
|
||||
}
|
||||
|
||||
return str.slice(0, num) + '...';
|
||||
}
|
||||
|
||||
truncateString("A-tisket a-tasket A green and yellow basket", 8);
|
||||
```
|
@ -0,0 +1,143 @@
|
||||
---
|
||||
id: a24c1a4622e3c05097f71d67
|
||||
title: 找出元素在排序後數組中的索引
|
||||
challengeType: 5
|
||||
forumTopicId: 16094
|
||||
dashedName: where-do-i-belong
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
數組(第一個參數)在排序後,將一個值(第二個參數)插入該數組,並使數組保持有序。返回這個新插入元素的最小索引值。 返回值應爲一個數字。
|
||||
|
||||
例如,`getIndexToIns([1,2,3,4], 1.5)` 應該返回 `1` 因爲1.5 大於 `1`(索引爲 0)且小於 `2`(索引爲 1)。
|
||||
|
||||
同樣地,`getIndexToIns([20,3,5], 19)` 應該返回 `2`。 因爲數組排序後會變成 `[3,5,20]`,而 `19` 小於 `20`(索引爲 2)且大於 `5`(索引爲 1)。
|
||||
|
||||
# --hints--
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` 應返回 `3`。
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([10, 20, 30, 40, 50], 35) === 3);
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 35) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` 應返回 `2`。
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([10, 20, 30, 40, 50], 30) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 30) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([40, 60], 50)` 應返回 `1`。
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([40, 60], 50) === 1);
|
||||
```
|
||||
|
||||
`getIndexToIns([40, 60], 50)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([40, 60], 50) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([3, 10, 5], 3)` 應返回 `0`。
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([3, 10, 5], 3) === 0);
|
||||
```
|
||||
|
||||
`getIndexToIns([3, 10, 5], 3)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([3, 10, 5], 3) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` 應返回 `2`。
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([5, 3, 20, 3], 5) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([5, 3, 20, 3], 5) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 20, 10], 19)` 應返回 `2`。
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([2, 20, 10], 19) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 20, 10], 19)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([2, 20, 10], 19) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 5, 10], 15)` 應返回 `3`。
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([2, 5, 10], 15) === 3);
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 5, 10], 15)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([2, 5, 10], 15) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([], 1)`應該返回 `0`。
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([], 1) === 0);
|
||||
```
|
||||
|
||||
`getIndexToIns([], 1)` 應返回一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([], 1) === 'number');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getIndexToIns(arr, num) {
|
||||
return num;
|
||||
}
|
||||
|
||||
getIndexToIns([40, 60], 50);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getIndexToIns(arr, num) {
|
||||
arr = arr.sort((a, b) => a - b);
|
||||
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
if (arr[i] >= num) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return arr.length;
|
||||
}
|
||||
|
||||
getIndexToIns([40, 60], 50);
|
||||
```
|
@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 5a661e0f1068aca922b3ef17
|
||||
title: 使用方括號訪問數組的元素
|
||||
challengeType: 1
|
||||
forumTopicId: 301149
|
||||
dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
所有數據結構的基本特性是,它們不僅可以存儲數據,還可以讓我們按需訪問存放在其中的數據。 我們已經學習瞭如何創建數組,現在讓我們來學習如何訪問數組中的數據。
|
||||
|
||||
我們先定義一個包含 3 個元素的數組:
|
||||
|
||||
```js
|
||||
let ourArray = ["a", "b", "c"];
|
||||
```
|
||||
|
||||
在數組中,內部的每個元素都有一個與之對應的索引(<dfn>index</dfn>)。 索引既是該元素在數組中的位置,也是我們訪問該元素的引用。 需要注意的是,JavaScript 數組的索引是從 0 開始的(這種從 0 開始的規則叫做 <dfn>zero-indexed</dfn>),即數組的第一個元素是在數組中的***第 0 個***位置,而不是第 1 個位置。 要從數組中獲取一個元素,我們可以在數組字面量後面加一個用方括號括起來的索引。不過習慣上,我們會通過表示數組的變量名來訪問,而不是直接通過字面量。 這種從數組中讀取元素的方式叫做方括號表示法(<dfn>bracket notation</dfn>)。 如果我們要從數組 `ourArray` 中取出數據 `a` 並將其賦值給另一個變量,可以這樣寫:
|
||||
|
||||
```js
|
||||
let ourVariable = ourArray[0];
|
||||
```
|
||||
|
||||
現在,變量 `ourVariable` 的值也爲 `a`。
|
||||
|
||||
通過索引,我們不僅可以獲取某個元素值,還可以用類似的寫法來*設置*一個索引位置的元素值:
|
||||
|
||||
```js
|
||||
ourArray[1] = "not b anymore";
|
||||
```
|
||||
|
||||
在上面的代碼中,我們用方括號表示法把索引爲 1 的元素從 `b` 改成了 `not b anymore`。 現在 `ourArray` 的值是 `["a", "not b anymore", "c"]`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
在本挑戰中,請將 `myArray` 中的第二個元素(索引爲 `1`)設置爲除了 `b` 以外的任意值。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray[0]` 應爲 `a`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[0], 'a');
|
||||
```
|
||||
|
||||
`myArray[1]` 不應爲 `b`。
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(myArray[1], 'b');
|
||||
```
|
||||
|
||||
`myArray[2]` 應爲 `c`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[2], 'c');
|
||||
```
|
||||
|
||||
`myArray[3]` 應爲 `d`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[3], 'd');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let myArray = ["a", "b", "c", "d"];
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
console.log(myArray);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let myArray = ["a", "b", "c", "d"];
|
||||
myArray[1] = "e";
|
||||
```
|
@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1a
|
||||
title: 使用方括號訪問屬性名稱
|
||||
challengeType: 1
|
||||
forumTopicId: 301150
|
||||
dashedName: access-property-names-with-bracket-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在關於對象的第一個挑戰中,我們提到可以在一對方括號中用一個變量作爲屬性名來訪問屬性的值。 假設一個超市收銀臺程序中有一個 `foods` 對象, 並且有一個函數會設置 `selectedFood`;如果我們需要查詢 `foods` 對象中,某種食物是否存在, 可以這樣實現:
|
||||
|
||||
```js
|
||||
let selectedFood = getCurrentFood(scannedItem);
|
||||
let inventory = foods[selectedFood];
|
||||
```
|
||||
|
||||
上述代碼會先讀取 `selectedFood` 變量的值,並返回 `foods` 對象中以該值命名的屬性所對應的屬性值。 若沒有以該值命名的屬性,則會返回 `undefined`。 有時候對象的屬性名在運行之前是不確定的,或者我們需要動態地訪問對象的屬性值。在這些場景下,方括號表示法就變得十分有用。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了 `checkInventory` 函數,它接受一個被掃描到的商品名作爲輸入參數。 請讓這個函數返回 `foods` 對象中,以 `scannedItem` 的值所命名的屬性對應的屬性值。 在本挑戰中,只有合理有效的屬性名會作爲參數傳入 `checkInventory`,因此你不需要處理參數無效的情況。
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkInventory` 應是一個函數。
|
||||
|
||||
```js
|
||||
assert.strictEqual(typeof checkInventory, 'function');
|
||||
```
|
||||
|
||||
`foods` 對象應只包含以下鍵值對:`apples: 25`、`oranges: 32`、`plums: 28`、`bananas: 13`、`grapes: 35`、`strawberries: 27`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(foods, {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
});
|
||||
```
|
||||
|
||||
`checkInventory("apples")` 應返回 `25`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('apples'), 25);
|
||||
```
|
||||
|
||||
`checkInventory("bananas")` 應返回 `13`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('bananas'), 13);
|
||||
```
|
||||
|
||||
`checkInventory("strawberries")` 應返回 `27`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('strawberries'), 27);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
|
||||
function checkInventory(scannedItem) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(checkInventory("apples"));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
|
||||
function checkInventory(scannedItem) {
|
||||
return foods[scannedItem];
|
||||
}
|
||||
```
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0e
|
||||
title: 使用 push() 和 unshift() 爲數組添加元素
|
||||
challengeType: 1
|
||||
forumTopicId: 301151
|
||||
dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
數組的長度與數組能包含的數據類型一樣,都是不固定的。 數組可以包含任意數量的元素,可以不限次數地往數組中添加元素或者從中移除元素。 總之,數組是可變的(<dfn>mutable</dfn>)。 在本挑戰中,我們要學習兩種修改數組的方法:`Array.push()` 和 `Array.unshift()`。
|
||||
|
||||
這兩個方法都接收一個或多個元素作爲參數,並會將參數中的元素添加到該數組中。 `push()` 方法會將元素插入到數組的末尾,而 `unshift()` 方法會將元素插入到數組的開頭。 請看以下例子:
|
||||
|
||||
```js
|
||||
let twentyThree = 'XXIII';
|
||||
let romanNumerals = ['XXI', 'XXII'];
|
||||
|
||||
romanNumerals.unshift('XIX', 'XX');
|
||||
```
|
||||
|
||||
`romanNumerals` 的值就變成了 `['XIX', 'XX', 'XXI', 'XXII']`。
|
||||
|
||||
```js
|
||||
romanNumerals.push(twentyThree);
|
||||
```
|
||||
|
||||
`romanNumerals` 的值現在就變成了 `['XIX', 'XX', 'XXI', 'XXII', 'XXIII']`。 請注意這裏,我們也可以使用變量作爲參數,這讓我們在動態修改數組數據時更加靈活。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個 `mixedNumbers` 函數,它接收一個數組作爲參數。 請修改這個函數,使用 `push()` 和 `unshift()` 來將 `'I', 2, 'three'` 插入到數組開頭;將 `7, 'VIII', 9` 插入到數組的末尾。最終這個函數的返回值就會是一個依次包含不同形式的 1-9 的數組。
|
||||
|
||||
# --hints--
|
||||
|
||||
`mixedNumbers(["IV", 5, "six"])` 應返回 `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
'I',
|
||||
2,
|
||||
'three',
|
||||
'IV',
|
||||
5,
|
||||
'six',
|
||||
7,
|
||||
'VIII',
|
||||
9
|
||||
]);
|
||||
```
|
||||
|
||||
`mixedNumbers` 函數中應調用 `push()` 方法。
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.push/));
|
||||
```
|
||||
|
||||
`mixedNumbers` 函數中應調用 `unshift()` 方法。
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.unshift/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function mixedNumbers(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return arr;
|
||||
}
|
||||
|
||||
console.log(mixedNumbers(['IV', 5, 'six']));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function mixedNumbers(arr) {
|
||||
arr.push(7,'VIII',9);
|
||||
arr.unshift('I',2,'three');
|
||||
return arr;
|
||||
}
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 587d78b3367417b2b2512b11
|
||||
title: 使用 splice() 添加元素
|
||||
challengeType: 1
|
||||
forumTopicId: 301152
|
||||
dashedName: add-items-using-splice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
還記得在上個挑戰中我們提到 `splice()` 方法最多可以接收 3 個參數嗎? 第三個參數可以是一個或多個元素,這些元素會被添加到數組中。 這樣,我們能夠便捷地將數組中的一個或多個連續元素換成其他的元素。
|
||||
|
||||
```js
|
||||
const numbers = [10, 11, 12, 12, 15];
|
||||
const startIndex = 3;
|
||||
const amountToDelete = 1;
|
||||
|
||||
numbers.splice(startIndex, amountToDelete, 13, 14);
|
||||
console.log(numbers);
|
||||
```
|
||||
|
||||
`12` 的第二個條目已被刪除,我們在同一索引處添加 `13` 和 `14`。 `numbers` 數組現在將會是 `[ 10, 11, 12, 13, 14, 15 ]`。
|
||||
|
||||
在上面的代碼中,數組一開始包含了若干數字。 接着,我們調用 `splice()` 方法,索引爲 (3) 的地方開始刪除元素,刪除的元素數量是 (1)。然後,(13, 14) 是在刪除位置插入的元素。 可以在 `amountToDelete` 後面傳入任意數量的元素(以逗號分隔),每個都會被插入到數組中。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個 `htmlColorNames` 函數,它以一個 HTML 顏色的數組作爲輸入參數。 請修改這個函數,使用 `splice()` 來移除數組中的前兩個元素,並在對應的位置上添加 `'DarkSalmon'` 和 `'BlanchedAlmond'`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`htmlColorNames` 應返回 `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
htmlColorNames([
|
||||
'DarkGoldenRod',
|
||||
'WhiteSmoke',
|
||||
'LavenderBlush',
|
||||
'PaleTurquoise',
|
||||
'FireBrick'
|
||||
]),
|
||||
[
|
||||
'DarkSalmon',
|
||||
'BlanchedAlmond',
|
||||
'LavenderBlush',
|
||||
'PaleTurquoise',
|
||||
'FireBrick'
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`htmlColorNames` 函數中應調用 `splice()` 方法。
|
||||
|
||||
```js
|
||||
assert(/.splice/.test(code));
|
||||
```
|
||||
|
||||
不應使用 `shift()` 或 `unshift()`。
|
||||
|
||||
```js
|
||||
assert(!/shift|unshift/.test(code));
|
||||
```
|
||||
|
||||
不應使用數組的方括號表示法。
|
||||
|
||||
```js
|
||||
assert(!/\[\d\]\s*=/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function htmlColorNames(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return arr;
|
||||
}
|
||||
|
||||
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurquoise', 'FireBrick']));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function htmlColorNames(arr) {
|
||||
arr.splice(0,2,'DarkSalmon', 'BlanchedAlmond');
|
||||
return arr;
|
||||
}
|
||||
```
|
@ -0,0 +1,124 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b18
|
||||
title: 將鍵值對添加到對象中
|
||||
challengeType: 1
|
||||
forumTopicId: 301153
|
||||
dashedName: add-key-value-pairs-to-javascript-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
對象(object)本質上是鍵值對(<dfn>key-value pair</dfn>)的集合。 或者說,一系列被映射到唯一標識符的數據就是對象;習慣上,唯一標識符叫做屬性(<dfn>property</dfn>)或者鍵(<dfn>key</dfn>);數據叫做值(<dfn>value</dfn>)。 讓我們來看一個簡單的例子:
|
||||
|
||||
```js
|
||||
const tekkenCharacter = {
|
||||
player: 'Hwoarang',
|
||||
fightingStyle: 'Tae Kwon Doe',
|
||||
human: true
|
||||
};
|
||||
```
|
||||
|
||||
上面的代碼定義了一個叫做 `tekkenCharacter` 的“鐵拳”遊戲人物對象。 它有三個屬性,每個屬性都對應一個特定的值。 如果我們想爲它再添加一個叫做 `origin` 的屬性,可以這樣寫:
|
||||
|
||||
```js
|
||||
tekkenCharacter.origin = 'South Korea';
|
||||
```
|
||||
|
||||
上面的代碼中,我們使用了點號表示法。 如果我們現在輸出 `tekkenCharacter` 對象,便可以看到它具有 `origin` 屬性。 接下來,因爲這個人物在遊戲中有着與衆不同的橘色頭髮, 我們可以通過方括號表示法來爲它添加這個屬性,像這樣:
|
||||
|
||||
```js
|
||||
tekkenCharacter['hair color'] = 'dyed orange';
|
||||
```
|
||||
|
||||
如果要設置的屬性中存在空格,或者要設置的屬性是一個變量,那我們必須使用方括號表示法(bracket notation)來爲對象添加屬性。 在上面的代碼中,我們把屬性(hair color)放到引號裏,以此來表示整個字符串都是需要設置的屬性。 如果我們不加上引號,那麼中括號裏的內容會被當作一個變量來解析,這個變量對應的值就會作爲要設置的屬性, 請看這段代碼:
|
||||
|
||||
```js
|
||||
const eyes = 'eye color';
|
||||
|
||||
tekkenCharacter[eyes] = 'brown';
|
||||
```
|
||||
|
||||
執行以上所有示例代碼後,對象會變成這樣:
|
||||
|
||||
```js
|
||||
{
|
||||
player: 'Hwoarang',
|
||||
fightingStyle: 'Tae Kwon Doe',
|
||||
human: true,
|
||||
origin: 'South Korea',
|
||||
'hair color': 'dyed orange',
|
||||
'eye color': 'brown'
|
||||
};
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經爲你創建了包含三個項目的 `foods` 對象。 請使用上述任意語法,來爲 foods 對象添加如下三個鍵值對:`bananas` 屬性,值爲 `13`;`grapes` 屬性,值爲 `35`;`strawberries` 屬性,值爲 `27`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`foods` 應爲一個對象。
|
||||
|
||||
```js
|
||||
assert(typeof foods === 'object');
|
||||
```
|
||||
|
||||
`foods` 應有一個值爲 `13` 的 `bananas` 屬性。
|
||||
|
||||
```js
|
||||
assert(foods.bananas === 13);
|
||||
```
|
||||
|
||||
`foods` 應有一個值爲 `35` 的 `grapes` 屬性。
|
||||
|
||||
```js
|
||||
assert(foods.grapes === 35);
|
||||
```
|
||||
|
||||
`foods` 應有一個值爲 `27` 的 `strawberries` 屬性。
|
||||
|
||||
```js
|
||||
assert(foods.strawberries === 27);
|
||||
```
|
||||
|
||||
應使用點號表示法或方括號表示法來設置對象的屬性。
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.search(/bananas:/) === -1 &&
|
||||
code.search(/grapes:/) === -1 &&
|
||||
code.search(/strawberries:/) === -1
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(foods);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28
|
||||
};
|
||||
|
||||
foods['bananas'] = 13;
|
||||
foods['grapes'] = 35;
|
||||
foods['strawberries'] = 27;
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b14
|
||||
title: 使用 indexOf() 檢查元素是否存在
|
||||
challengeType: 1
|
||||
forumTopicId: 301154
|
||||
dashedName: check-for-the-presence-of-an-element-with-indexof
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
由於數組隨時都可以修改或發生 *mutated*,我們很難保證某個數據始終處於數組中的特定位置,甚至不能保證該元素是否還存在於該數組中。 好消息是,JavaScript 爲我們提供了內置方法 `indexOf()`。 這個方法讓我們可以方便地檢查某個元素是否存在於數組中。 `indexOf()` 方法接受一個元素作爲輸入參數,並返回該元素在數組中的位置(索引);若該元素不存在於數組中則返回 `-1`。
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
|
||||
|
||||
fruits.indexOf('dates');
|
||||
fruits.indexOf('oranges');
|
||||
fruits.indexOf('pears');
|
||||
```
|
||||
|
||||
`indexOf('dates')` 返回 `-1`,`indexOf('oranges')` 返回 `2`,`indexOf('pears')` 返回 `1` (每個元素存在的第一個索引)。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`indexOf()` 在快速檢查一個數組中是否存在某個元素時非常有用。 我們已經定義了一個 `quickCheck` 函數,它接受一個數組和一個元素作爲輸入參數。 請通過 `indexOf()` 方法修改這個函數,使得當傳入的參數在數組中存在時返回 `true`,否則返回 `false`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`quickCheck` 函數應返回一個布爾值(`true` 或 `false`),而不是一個字符串(`"true"` 或 `"false"`)。
|
||||
|
||||
```js
|
||||
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
|
||||
```
|
||||
|
||||
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'),
|
||||
false
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck(["onions", "squash", "shallots"], "onions")` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
quickCheck(['onions', 'squash', 'shallots'], 'onions'),
|
||||
true
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck([3, 5, 9, 125, 45, 2], 125)` 應返回 `true`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
|
||||
```
|
||||
|
||||
`quickCheck([true, false, false], undefined)` 應返回 `false`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([true, false, false], undefined), false);
|
||||
```
|
||||
|
||||
`quickCheck` 函數中應使用 `indexOf()` 方法。
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function quickCheck(arr, elem) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function quickCheck(arr, elem) {
|
||||
return arr.indexOf(elem) >= 0;
|
||||
}
|
||||
```
|
@ -0,0 +1,153 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1c
|
||||
title: 檢查對象是否具有某個屬性
|
||||
challengeType: 1
|
||||
forumTopicId: 301155
|
||||
dashedName: check-if-an-object-has-a-property
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們已經學習瞭如何添加、修改和移除對象中的屬性。 但如果我們想知道一個對象中是否包含某個屬性呢? JavaScript 爲我們提供了兩種不同的方式來實現這個功能: 一個是通過 `hasOwnProperty()` 方法,另一個是使用 `in` 關鍵字。 假如我們有一個 `users` 對象,爲檢查它是否含有 `Alan` 屬性,可以這樣寫:
|
||||
|
||||
```js
|
||||
users.hasOwnProperty('Alan');
|
||||
'Alan' in users;
|
||||
```
|
||||
|
||||
這兩者結果都應該爲 `true`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個包含若干用戶信息的 `users` 對象和一個 `isEveryoneHere` 函數,該函數接收 `users` 對象作爲參數。 請完成該函數使其在 `users` 對象中同時包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 四個屬性時才返回 `true`,否則返回 `false`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`users` 對象應該只包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 個屬性。
|
||||
|
||||
```js
|
||||
assert(
|
||||
'Alan' in users &&
|
||||
'Jeff' in users &&
|
||||
'Sarah' in users &&
|
||||
'Ryan' in users &&
|
||||
Object.keys(users).length === 4
|
||||
);
|
||||
```
|
||||
|
||||
`isEveryoneHere` 函數在 `users` 對象包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 個屬性時應返回 `true`。
|
||||
|
||||
```js
|
||||
assert(isEveryoneHere(users) === true);
|
||||
```
|
||||
|
||||
`isEveryoneHere` 函數在 `users` 對象不包含 `Alan` 時應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
delete users.Alan;
|
||||
return isEveryoneHere(users);
|
||||
})() === false
|
||||
);
|
||||
```
|
||||
|
||||
`isEveryoneHere` 函數在 `users` 對象不包含 `Jeff` 時應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
delete users.Jeff;
|
||||
return isEveryoneHere(users);
|
||||
})() === false
|
||||
);
|
||||
```
|
||||
|
||||
`isEveryoneHere` 函數在 `users` 對象不包含 `Sarah` 時應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
delete users.Sarah;
|
||||
return isEveryoneHere(users);
|
||||
})() === false
|
||||
);
|
||||
```
|
||||
|
||||
`isEveryoneHere` 函數在 `users` 對象不包含 `Ryan` 時應返回 `false`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
delete users.Ryan;
|
||||
return isEveryoneHere(users);
|
||||
})() === false
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: true
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: true
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function isEveryoneHere(obj) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(isEveryoneHere(users));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: true
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: true
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function isEveryoneHere(obj) {
|
||||
return [
|
||||
'Alan',
|
||||
'Jeff',
|
||||
'Sarah',
|
||||
'Ryan'
|
||||
].every(i => obj.hasOwnProperty(i));
|
||||
}
|
||||
|
||||
console.log(isEveryoneHere(users));
|
||||
```
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b17
|
||||
title: 使用展開運算符合並數組
|
||||
challengeType: 1
|
||||
forumTopicId: 301156
|
||||
dashedName: combine-arrays-with-the-spread-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
展開語法(<dfn>spread</dfn>)的另一個重要用途是合併數組,或者將某個數組的所有元素插入到另一個數組的任意位置。 我們也可以使用 ES5 的語法連接兩個數組,但只能讓它們首尾相接。 而展開語法可以讓這樣的操作變得極其簡單:
|
||||
|
||||
```js
|
||||
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
|
||||
|
||||
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
|
||||
```
|
||||
|
||||
`thatArray` 會有值 `['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']`
|
||||
|
||||
使用展開語法,我們就可以很方便的實現一個用傳統方法會寫得很複雜且冗長的操作。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個返回 `sentence` 變量的 `spreadOut` 函數。 請修改這個函數,利用 <dfn>spread</dfn> 使該函數返回數組 `['learning', 'to', 'code', 'is', 'fun']`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`spreadOut` 應返回 `["learning", "to", "code", "is", "fun"]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
|
||||
```
|
||||
|
||||
`spreadOut` 函數裏應用到展開語法。
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function spreadOut() {
|
||||
let fragment = ['to', 'code'];
|
||||
let sentence; // Change this line
|
||||
return sentence;
|
||||
}
|
||||
|
||||
console.log(spreadOut());
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function spreadOut() {
|
||||
let fragment = ['to', 'code'];
|
||||
let sentence = ['learning', ...fragment, 'is', 'fun'];
|
||||
return sentence;
|
||||
}
|
||||
```
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b13
|
||||
title: 使用展開運算符複製數組
|
||||
challengeType: 1
|
||||
forumTopicId: 301157
|
||||
dashedName: copy-an-array-with-the-spread-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`slice()` 可以讓我們從一個數組中選擇一些元素來複制到新數組中,而 ES6 中又引入了一個簡潔且可讀性強的語法:展開運算符(<dfn>spread operator</dfn>),它能讓我們方便地複製數組中的*所有*元素。 展開語法寫出來是這樣:`...`
|
||||
|
||||
我們可以用展開運算符來複制數組:
|
||||
|
||||
```js
|
||||
let thisArray = [true, true, undefined, false, null];
|
||||
let thatArray = [...thisArray];
|
||||
```
|
||||
|
||||
`thatArray` 等於 `[true, true, undefined, false, null]`。 `thisArray` 保持不變, `thatArray` 包含與 `thisArray` 相同的元素。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個 `copyMachine` 函數,它接受 `arr`(一個數組)和 `num`(一個數字)作爲輸入參數。 該函數需要返回一個由 `num` 個 `arr` 組成的新的二維數組。 同時,我們寫好了大致的流程,只是細節實現還沒有寫完。 請修改這個函數,使用展開語法,使該函數能正常工作(提示:我們已經學到過的一個方法很適合用在這裏)!
|
||||
|
||||
# --hints--
|
||||
|
||||
`copyMachine([true, false, true], 2)` 應返回 `[[true, false, true], [true, false, true]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
[true, false, true],
|
||||
[true, false, true]
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([1, 2, 3], 5)` 應返回 `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
[1, 2, 3],
|
||||
[1, 2, 3],
|
||||
[1, 2, 3],
|
||||
[1, 2, 3],
|
||||
[1, 2, 3]
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([true, true, null], 1)` 應返回 `[[true, true, null]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
|
||||
```
|
||||
|
||||
`copyMachine(["it works"], 3)` 應返回 `[["it works"], ["it works"], ["it works"]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
['it works'],
|
||||
['it works'],
|
||||
['it works']
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine` 函數中應對 `arr` 使用展開運算符(`spread operator`)。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.\.\.arr/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function copyMachine(arr, num) {
|
||||
let newArr = [];
|
||||
while (num >= 1) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
num--;
|
||||
}
|
||||
return newArr;
|
||||
}
|
||||
|
||||
console.log(copyMachine([true, false, true], 2));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function copyMachine(arr,num){
|
||||
let newArr=[];
|
||||
while(num >=1){
|
||||
newArr.push([...arr]);
|
||||
num--;
|
||||
}
|
||||
return newArr;
|
||||
}
|
||||
console.log(copyMachine([true, false, true], 2));
|
||||
```
|
@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 587d7b7a367417b2b2512b12
|
||||
title: 使用 slice() 複製數組元素
|
||||
challengeType: 1
|
||||
forumTopicId: 301158
|
||||
dashedName: copy-array-items-using-slice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
接下來我們要介紹 `slice()` 方法。 `slice()` 不會修改數組,而是會複製,或者說*提取(extract)*給定數量的元素到一個新數組。 `slice()` 只接收 2 個輸入參數:第一個是開始提取元素的位置(索引),第二個是提取元素的結束位置(索引)。 提取的元素中不包括第二個參數所對應的元素。 如下示例:
|
||||
|
||||
```js
|
||||
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
|
||||
|
||||
let todaysWeather = weatherConditions.slice(1, 3);
|
||||
```
|
||||
|
||||
`todaysWeather` 值爲 `['snow', 'sleet']`,`weatherConditions` 值仍然爲 `['rain', 'snow', 'sleet', 'hail', 'clear']`。
|
||||
|
||||
在上面的代碼中,我們從一個數組中提取了一些元素,並用這些元素創建了一個新數組。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個 `forecast` 函數,它接受一個數組作爲參數。 請修改這個函數,利用 `slice()` 從輸入的數組中提取信息,最終返回一個包含元素 `warm` 和 `sunny` 的新數組。
|
||||
|
||||
# --hints--
|
||||
|
||||
`forecast` 應返回 `["warm", "sunny"]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']),
|
||||
['warm', 'sunny']
|
||||
);
|
||||
```
|
||||
|
||||
`forecast` 函數中應使用 `slice()` 方法。
|
||||
|
||||
```js
|
||||
assert(/\.slice\(/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function forecast(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function forecast(arr) {
|
||||
return arr.slice(2,4);
|
||||
}
|
||||
```
|
@ -0,0 +1,218 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b16
|
||||
title: 創建複雜的多維數組
|
||||
challengeType: 1
|
||||
forumTopicId: 301159
|
||||
dashedName: create-complex-multi-dimensional-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
很好! 你現在已經學到很多關於數組的知識了, 但這些只是個開始。我們將在接下來的中挑戰中學到更多與數組相關的知識。 在繼續學習對象(<dfn>Objects</dfn>)之前,讓我們再花一點時間瞭解下更復雜的數組嵌套。
|
||||
|
||||
數組的一個強大的特性是,它可以包含其他數組,甚至完全由其他數組組成。 在上一個挑戰中,我們已經接觸到了包含數組的數組,但它還算是比較簡單的。 數組中的數組還可以再包含其他數組,即可以嵌套任意多層數組。 習慣上,我們稱這種數據結構爲<dfn>多維(multi-dimensional)數組</dfn>或嵌套(nested)數組。 請看如下的示例:
|
||||
|
||||
```js
|
||||
let nestedArray = [
|
||||
['deep'],
|
||||
[
|
||||
['deeper'], ['deeper']
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest'], ['deepest']
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest-est?']
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
```
|
||||
|
||||
`deep` 數組已嵌套 2 層。 `deeper` 數組嵌套了 3 層。 `deepest` 數組嵌套了 3 層, `deepest-est?` 嵌套了 5 層。
|
||||
|
||||
雖然這個例子看起來錯綜複雜,不過,尤其是在處理大量數據的時候,這種數據結構還是會用到的。 儘管結構複雜,不過我們仍可以通過方括號表示法來訪問嵌套得最深的數組:
|
||||
|
||||
```js
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
```
|
||||
|
||||
控制檯打印的是字符串 `deepest-est?`。 既然我們知道數據的位置,當然,我們也可以修改它:
|
||||
|
||||
```js
|
||||
nestedArray[2][1][0][0][0] = 'deeper still';
|
||||
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
```
|
||||
|
||||
現在控制檯打印的是 `deeper still`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個叫做 `myNestedArray` 的數組變量。 請修改 `myNestedArray`,使用字符串(<dfn>string</dfn>)、數字(<dfn>number</dfn>)或布爾值(<dfn>boolean</dfn>)的任意組合作爲數組的元素,並讓 myNestedArray 剛好有 5 層(注意,最外層的數組是第 1 層)。 同時,請在第 3 層的數組中包含字符串 `deep`;在第 4 層的數組中包含字符串 `deeper`,在第 5 層的數組中包含字符串 `deepest`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myNestedArray` 中的數據元素應只包含字符串、數字或者布爾值。
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
(function (arr) {
|
||||
let flattened = (function flatten(arr) {
|
||||
const flat = [].concat(...arr);
|
||||
return flat.some(Array.isArray) ? flatten(flat) : flat;
|
||||
})(arr);
|
||||
for (let i = 0; i < flattened.length; i++) {
|
||||
if (
|
||||
typeof flattened[i] !== 'number' &&
|
||||
typeof flattened[i] !== 'string' &&
|
||||
typeof flattened[i] !== 'boolean'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
})(myNestedArray),
|
||||
true
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 應剛好包含 5 層嵌套數組。
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
(function (arr) {
|
||||
let depth = 0;
|
||||
function arrayDepth(array, i, d) {
|
||||
if (Array.isArray(array[i])) {
|
||||
arrayDepth(array[i], 0, d + 1);
|
||||
} else {
|
||||
depth = d > depth ? d : depth;
|
||||
}
|
||||
if (i < array.length) {
|
||||
arrayDepth(array, i + 1, d);
|
||||
}
|
||||
}
|
||||
arrayDepth(arr, 0, 0);
|
||||
return depth;
|
||||
})(myNestedArray),
|
||||
4
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 中應只有一個字符串 `deep`,並且應出現在第 3 層數組中。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deep').length === 1 &&
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deep')[0] === 2
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 中應只有一個字符串 `deeper`,並且應出現在第 4 層數組中。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deeper').length === 1 &&
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deeper')[0] === 3
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 中應只有一個字符串 `deepest`,並且應出現在第 5 層數組中。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deepest').length === 1 &&
|
||||
(function howDeep(array, target, depth = 0) {
|
||||
return array.reduce((combined, current) => {
|
||||
if (Array.isArray(current)) {
|
||||
return combined.concat(howDeep(current, target, depth + 1));
|
||||
} else if (current === target) {
|
||||
return combined.concat(depth);
|
||||
} else {
|
||||
return combined;
|
||||
}
|
||||
}, []);
|
||||
})(myNestedArray, 'deepest')[0] === 4
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let myNestedArray = [
|
||||
// Only change code below this line
|
||||
['unshift', false, 1, 2, 3, 'complex', 'nested'],
|
||||
['loop', 'shift', 6, 7, 1000, 'method'],
|
||||
['concat', false, true, 'spread', 'array'],
|
||||
['mutate', 1327.98, 'splice', 'slice', 'push'],
|
||||
['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth']
|
||||
// Only change code above this line
|
||||
];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let myNestedArray = [
|
||||
['unshift', ['deep', ['deeper', ['deepest']]],false, 1, 2, 3, 'complex', 'nested'],
|
||||
['loop', 'shift', 6, 7, 1000, 'method'],
|
||||
['concat', false, true, 'spread', 'array'],
|
||||
['mutate', 1327.98, 'splice', 'slice', 'push'],
|
||||
['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth']
|
||||
];
|
||||
```
|
@ -0,0 +1,111 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1e
|
||||
title: 使用 Object.keys() 生成由對象的所有屬性組成的數組
|
||||
challengeType: 1
|
||||
forumTopicId: 301160
|
||||
dashedName: generate-an-array-of-all-object-keys-with-object-keys
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們可以給 `Object.keys()` 方法傳入一個對象作爲參數,來生成包含對象所有鍵的數組。 這會返回一個由對象中所有屬性(字符串)組成的數組。 需要注意的是,數組中元素的順序是不確定的。
|
||||
|
||||
# --instructions--
|
||||
|
||||
請完成 `getArrayOfUsers` 函數的實現,使其返回一個由輸入對象中的所有屬性所組成的數組。
|
||||
|
||||
# --hints--
|
||||
|
||||
`users` 對象應該只包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 這 4 個屬性。
|
||||
|
||||
```js
|
||||
assert(
|
||||
'Alan' in users &&
|
||||
'Jeff' in users &&
|
||||
'Sarah' in users &&
|
||||
'Ryan' in users &&
|
||||
Object.keys(users).length === 4
|
||||
);
|
||||
```
|
||||
|
||||
`getArrayOfUsers` 函數應返回一個包含 `users` 對象中所有屬性的數組。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
users.Sam = {};
|
||||
users.Lewis = {};
|
||||
let R = getArrayOfUsers(users);
|
||||
return (
|
||||
R.indexOf('Alan') !== -1 &&
|
||||
R.indexOf('Jeff') !== -1 &&
|
||||
R.indexOf('Sarah') !== -1 &&
|
||||
R.indexOf('Ryan') !== -1 &&
|
||||
R.indexOf('Sam') !== -1 &&
|
||||
R.indexOf('Lewis') !== -1
|
||||
);
|
||||
})() === true
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: false
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function getArrayOfUsers(obj) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(getArrayOfUsers(users));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: false
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function getArrayOfUsers(obj) {
|
||||
return Object.keys(obj);
|
||||
}
|
||||
|
||||
console.log(getArrayOfUsers(users));
|
||||
```
|
@ -0,0 +1,138 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b15
|
||||
title: 使用 for 循環遍歷數組中的全部元素
|
||||
challengeType: 1
|
||||
forumTopicId: 301161
|
||||
dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
使用數組時,我們經常需要遍歷數組的所有元素來找出我們需要的一個或多個元素,抑或是對數組執行一些特定的操作。 JavaScript 爲我們提供了幾個內置的方法,它們以不同的方式遍歷數組,以便我們可以用於不同的場景(如 `every()`、`forEach()`、`map()` 等等)。 然而,最簡單的 `for` 循環不僅能實現上述這些方法的功能,而且相比之下也會更加靈活。
|
||||
|
||||
請看以下的例子:
|
||||
|
||||
```js
|
||||
function greaterThanTen(arr) {
|
||||
let newArr = [];
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
if (arr[i] > 10) {
|
||||
newArr.push(arr[i]);
|
||||
}
|
||||
}
|
||||
return newArr;
|
||||
}
|
||||
|
||||
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
|
||||
```
|
||||
|
||||
在這個函數中,我們用一個 `for` 循環來遍歷數組,逐一對其中的元素進行判斷。 通過上面的代碼,我們可以找出數組中大於 `10` 的所有元素,並返回一個包含這些元素的新數組 `[12, 14, 80]`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了 `filteredArray` 函數,它接受一個嵌套的數組 `arr` 和一個 `elem` 作爲參數,並要返回一個新數組。 `arr` 數組中嵌套的數組裏可能包含 `elem` 元素,也可能不包含。 請修改該函數,用一個 `for` 循環來做篩選,使函數返回一個由 `arr` 中不包含 `elem` 的數組所組成的新數組。
|
||||
|
||||
# --hints--
|
||||
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` 應返回 `[[10, 8, 3], [14, 6, 23]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
filteredArray(
|
||||
[
|
||||
[10, 8, 3],
|
||||
[14, 6, 23],
|
||||
[3, 18, 6]
|
||||
],
|
||||
18
|
||||
),
|
||||
[
|
||||
[10, 8, 3],
|
||||
[14, 6, 23]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)` 應返回 `[["flutes", 4]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
filteredArray(
|
||||
[
|
||||
['trumpets', 2],
|
||||
['flutes', 4],
|
||||
['saxophones', 2]
|
||||
],
|
||||
2
|
||||
),
|
||||
[['flutes', 4]]
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")` 應返回 `[["amy", "beth", "sam"]]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
filteredArray(
|
||||
[
|
||||
['amy', 'beth', 'sam'],
|
||||
['dave', 'sean', 'peter']
|
||||
],
|
||||
'peter'
|
||||
),
|
||||
[['amy', 'beth', 'sam']]
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` 應返回 `[]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
filteredArray(
|
||||
[
|
||||
[3, 2, 3],
|
||||
[1, 6, 3],
|
||||
[3, 13, 26],
|
||||
[19, 3, 9]
|
||||
],
|
||||
3
|
||||
),
|
||||
[]
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray` 函數中應使用 `for` 循環。
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function filteredArray(arr, elem) {
|
||||
let newArr = [];
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return newArr;
|
||||
}
|
||||
|
||||
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function filteredArray(arr, elem) {
|
||||
let newArr = [];
|
||||
for (let i = 0; i<arr.length; i++) {
|
||||
if (arr[i].indexOf(elem) < 0) {
|
||||
newArr.push(arr[i]);
|
||||
}
|
||||
}
|
||||
return newArr;
|
||||
}
|
||||
```
|
@ -0,0 +1,138 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1d
|
||||
title: 使用 for...in 語句遍歷對象
|
||||
challengeType: 1
|
||||
forumTopicId: 301162
|
||||
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
如果我們想要遍歷對象中的所有屬性, 只需要使用 JavaScript 中的 <dfn>for...in</dfn> 語句即可。 以遍歷 `users` 對象的屬性爲例:
|
||||
|
||||
```js
|
||||
for (let user in users) {
|
||||
console.log(user);
|
||||
}
|
||||
```
|
||||
|
||||
這將在控制檯打印 `Alan`、`Jeff`、`Sarah` 和 `Ryan` - 每個值佔一行。
|
||||
|
||||
在上面的代碼中,我們定義了一個 `user` 變量。 可以觀察到,這個變量在遍歷對象的語句執行過程中會一直被重置並賦予新值,結果就是不同的用戶名打印到了 console 中。
|
||||
|
||||
**注意:**對象中的鍵是無序的,這與數組不同。 因此,一個對象中某個屬性的位置,或者說它出現的相對順序,在引用或訪問該屬性時是不確定的。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個 `countOnline` 函數,它接收一個 users 對象參數。 請在其中使用 <dfn>for...in</dfn> 語句來遍歷傳入函數的 users 對象中的用戶,並返回 `online` 屬性爲 `true` 的用戶數量。 以下是一個傳入 `countOnline` 函數的對象示例, 注意每個用戶都有 `online` 屬性,其屬性值爲 `true` 或 `false`:
|
||||
|
||||
```js
|
||||
{
|
||||
Alan: {
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
online: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
函數 `countOnline` 中應使用 `for in` 語句遍歷傳入的對象的對象鍵。
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(
|
||||
/for\s*\(\s*(var|let|const)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)/
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
當傳入 `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` 時,函數 `countOnline` 應該返回 `1`。
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj1) === 1);
|
||||
```
|
||||
|
||||
當傳入 `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` 時,函數 `countOnline` 應該返回 `2`。
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj2) === 2);
|
||||
```
|
||||
|
||||
當傳入 `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` 時,函數 `countOnline` 應該返回 `0`。
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj3) === 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const usersObj1 = {
|
||||
Alan: {
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
online: false
|
||||
}
|
||||
}
|
||||
|
||||
const usersObj2 = {
|
||||
Alan: {
|
||||
online: true
|
||||
},
|
||||
Jeff: {
|
||||
online: false
|
||||
},
|
||||
Sarah: {
|
||||
online: true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const usersObj3 = {
|
||||
Alan: {
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
online: false
|
||||
},
|
||||
Sarah: {
|
||||
online: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function countOnline(usersObj) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function countOnline(usersObj) {
|
||||
let online = 0;
|
||||
for(let user in usersObj){
|
||||
if(usersObj[user].online) {
|
||||
online++;
|
||||
}
|
||||
}
|
||||
return online;
|
||||
}
|
||||
```
|
@ -0,0 +1,112 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1f
|
||||
title: 修改存儲在對象中的數組
|
||||
challengeType: 1
|
||||
forumTopicId: 301163
|
||||
dashedName: modify-an-array-stored-in-an-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們已經學習了 JavaScript 對象的這些基本操作: 添加、修改、移除鍵值對、檢查某個屬性是否存在、遍歷對象的所有屬性。 在繼續學習 JavaScript 的過程中,我們會了解對象的更多用法。 另外,在之後的數據結構課程中,我們還會學習 ES6 的 <dfn>Map</dfn> 和 <dfn>Set</dfn>。 這兩種數據結構與我們現在學到的對象十分類似,但它們在對象的基礎上提供了一些額外的功能。 目前,我們已經學習了數組和對象的基礎知識,讓我們試着來用所學的知識解決一些更復雜的問題。
|
||||
|
||||
# --instructions--
|
||||
|
||||
請看一下代碼編輯器中我們爲你寫好的對象。 `user` 對象包含 3 個屬性; `data` 對象包含 5 個屬性,其中包含一個叫做 `friends` 的數組。 這就是對象作爲數據結構所展現出的靈活性。 我們已經寫好了 `addFriend` 函數的一部分, 請你完成這個函數,使其接受一個 `user` 對象,將 `friend` 參數中的名字添加到 `user.data.friends` 數組中並返回該數組。
|
||||
|
||||
# --hints--
|
||||
|
||||
`user` 對象應該包含 `name`、`age` 和 `data` 三個屬性。
|
||||
|
||||
```js
|
||||
assert('name' in user && 'age' in user && 'data' in user);
|
||||
```
|
||||
|
||||
`addFriend` 函數應該接受一個 `user` 對象和一個 `friend` 字符串作爲輸入參數,並將這個字符串插入到 `user` 對象的 `friends` 數組中。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
let L1 = user.data.friends.length;
|
||||
addFriend(user, 'Sean');
|
||||
let L2 = user.data.friends.length;
|
||||
return L2 === L1 + 1;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
`addFriend(user, "Pete")` 應該返回 `["Sam", "Kira", "Tomo", "Pete"]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
(function () {
|
||||
delete user.data.friends;
|
||||
user.data.friends = ['Sam', 'Kira', 'Tomo'];
|
||||
return addFriend(user, 'Pete');
|
||||
})(),
|
||||
['Sam', 'Kira', 'Tomo', 'Pete']
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let user = {
|
||||
name: 'Kenneth',
|
||||
age: 28,
|
||||
data: {
|
||||
username: 'kennethCodesAllDay',
|
||||
joinDate: 'March 26, 2016',
|
||||
organization: 'freeCodeCamp',
|
||||
friends: [
|
||||
'Sam',
|
||||
'Kira',
|
||||
'Tomo'
|
||||
],
|
||||
location: {
|
||||
city: 'San Francisco',
|
||||
state: 'CA',
|
||||
country: 'USA'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function addFriend(userObj, friend) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
console.log(addFriend(user, 'Pete'));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let user = {
|
||||
name: 'Kenneth',
|
||||
age: 28,
|
||||
data: {
|
||||
username: 'kennethCodesAllDay',
|
||||
joinDate: 'March 26, 2016',
|
||||
organization: 'freeCodeCamp',
|
||||
friends: [
|
||||
'Sam',
|
||||
'Kira',
|
||||
'Tomo'
|
||||
],
|
||||
location: {
|
||||
city: 'San Francisco',
|
||||
state: 'CA',
|
||||
country: 'USA'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function addFriend(userObj, friend) {
|
||||
userObj.data.friends.push(friend);
|
||||
return userObj.data.friends;
|
||||
}
|
||||
```
|
@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b19
|
||||
title: 修改嵌套在對象中的對象
|
||||
challengeType: 1
|
||||
forumTopicId: 301164
|
||||
dashedName: modify-an-object-nested-within-an-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
現在我們來看一個稍複雜的對象。 在對象中,我們也可以嵌套任意層數的對象,對象的屬性值可以是 JavaScript 支持的任意類型,包括數組和其他對象。 請看以下例子:
|
||||
|
||||
```js
|
||||
let nestedObject = {
|
||||
id: 28802695164,
|
||||
date: 'December 31, 2016',
|
||||
data: {
|
||||
totalUsers: 99,
|
||||
online: 80,
|
||||
onlineStatus: {
|
||||
active: 67,
|
||||
away: 13,
|
||||
busy: 8
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
`nestedObject` 有 3 個屬性:`id`(屬性值爲數字)、`date`(屬性值爲字符串)、`data`(屬性值爲嵌套的對象)。 雖然對象中的數據可能很複雜,我們仍能使用上一個挑戰中講到的寫法來訪問我們需要的信息。 如果我們想把嵌套在 `onlineStatus` 中 `busy` 的屬性值改爲 `10`,可以用點號表示法來這樣實現:
|
||||
|
||||
```js
|
||||
nestedObject.data.onlineStatus.busy = 10;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個 `userActivity` 對象,它包含了另一個對象。 請將 `online` 的屬性值改爲 `45`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`userActivity` 應包含 `id`、`date` 和 `data` 屬性。
|
||||
|
||||
```js
|
||||
assert(
|
||||
'id' in userActivity && 'date' in userActivity && 'data' in userActivity
|
||||
);
|
||||
```
|
||||
|
||||
`userActivity` 應包含 `data` 屬性,其屬性值應爲包含 `totalUsers` 和 `online` 屬性的對象。
|
||||
|
||||
```js
|
||||
assert('totalUsers' in userActivity.data && 'online' in userActivity.data);
|
||||
```
|
||||
|
||||
`userActivity` 的 `data` 屬性值中的 `online` 屬性值應被改爲 `45`。
|
||||
|
||||
```js
|
||||
assert(userActivity.data.online === 45);
|
||||
```
|
||||
|
||||
應使用點號表示法或方括號表示法來修改 `online` 屬性值。
|
||||
|
||||
```js
|
||||
assert.strictEqual(code.search(/online: 45/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let userActivity = {
|
||||
id: 23894201352,
|
||||
date: 'January 1, 2017',
|
||||
data: {
|
||||
totalUsers: 51,
|
||||
online: 42
|
||||
}
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(userActivity);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let userActivity = {
|
||||
id: 23894201352,
|
||||
date: 'January 1, 2017',
|
||||
data: {
|
||||
totalUsers: 51,
|
||||
online: 42
|
||||
}
|
||||
};
|
||||
|
||||
userActivity.data.online = 45;
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0f
|
||||
title: 使用 pop() 和 shift() 從數組中刪除元素
|
||||
challengeType: 1
|
||||
forumTopicId: 301165
|
||||
dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`push()` 和 `unshift()` 都有一個與它們作用相反的函數:`pop()` 和 `shift()`。 與插入元素相反,`pop()` 會從數組的末尾*移除*一個元素,而 `shift()` 會從數組的開頭移除一個元素。 `pop()` 和 `shift()` 與 `push()` 和 `unshift()` 的關鍵區別在於,用於刪除元素的方法不接收參數,而且每次只能刪除數組中的一個元素。
|
||||
|
||||
讓我們來看以下的例子:
|
||||
|
||||
```js
|
||||
let greetings = ['whats up?', 'hello', 'see ya!'];
|
||||
|
||||
greetings.pop();
|
||||
```
|
||||
|
||||
`greetings` 值爲 `['whats up?', 'hello']`。
|
||||
|
||||
```js
|
||||
greetings.shift();
|
||||
```
|
||||
|
||||
`greetings` 值爲 `['hello']`。
|
||||
|
||||
這些用於刪除數組元素的方法會返回被刪除的元素:
|
||||
|
||||
```js
|
||||
let popped = greetings.pop();
|
||||
```
|
||||
|
||||
`greetings` 值爲 `[]`,`popped` 值爲 `hello`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個 `popShift` 函數,它接收一個數組作爲輸入參數並返回一個新的數組。 請修改這個函數,使用 `pop()` 和 `shift()` 來移除輸入的數組中的第一個元素和最後一個元素,並將這兩個被移除的元素分別賦值給對應的變量,使得最終返回的數組裏包含這兩個值。
|
||||
|
||||
# --hints--
|
||||
|
||||
`popShift(["challenge", "is", "not", "complete"])` 應返回 `["challenge", "complete"]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
'challenge',
|
||||
'complete'
|
||||
]);
|
||||
```
|
||||
|
||||
`popShift` 函數中應使用 `pop()` 方法。
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
|
||||
```
|
||||
|
||||
`popShift` 函數中應使用 `shift()` 方法。
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function popShift(arr) {
|
||||
let popped; // Change this line
|
||||
let shifted; // Change this line
|
||||
return [shifted, popped];
|
||||
}
|
||||
|
||||
console.log(popShift(['challenge', 'is', 'not', 'complete']));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function popShift(arr) {
|
||||
let popped = arr.pop(); // Change this line
|
||||
let shifted = arr.shift(); // Change this line
|
||||
return [shifted, popped];
|
||||
}
|
||||
```
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b10
|
||||
title: 使用 splice() 刪除元素
|
||||
challengeType: 1
|
||||
forumTopicId: 301166
|
||||
dashedName: remove-items-using-splice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在之前的挑戰中,我們已經學習瞭如何用 `shift()` 和 `pop()` 從數組的開頭或末尾移除元素。 但如果我們想刪除數組中間的一個元素, 或者想一次刪除多個元素,該如何操作呢? 這時候我們就需要使用 `splice()` 方法了, `splice()` 可以讓我們從數組中的任意位置**連續刪除任意數量的元素**。
|
||||
|
||||
`splice()` 最多可以接受 3 個參數,但現在我們先關注前兩個。 `splice()` 接收的前兩個參數是整數,表示正在調用 的`splice()` 數組中的元素的索引或位置。 別忘了,數組的索引是*從 0 開始的*,所以我們要用 `0` 來表示數組中的第一個元素。 `splice()` 的第一個參數代表從數組中的哪個索引開始移除元素,而第二個參數表示要從數組中的這個位置開始刪除多少個元素。 例如:
|
||||
|
||||
```js
|
||||
let array = ['today', 'was', 'not', 'so', 'great'];
|
||||
|
||||
array.splice(2, 2);
|
||||
```
|
||||
|
||||
這裏我們移除 2 個元素,首先是第三個元素(索引爲 2)。 `array` 會有值 `['today', 'was', 'great']`。
|
||||
|
||||
`splice()` 不僅會修改調用該方法的數組,還會返回一個包含被移除元素的數組:
|
||||
|
||||
```js
|
||||
let array = ['I', 'am', 'feeling', 'really', 'happy'];
|
||||
|
||||
let newArray = array.splice(3, 2);
|
||||
```
|
||||
|
||||
`newArray` 值爲 `['really', 'happy']`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了數組 `arr`。 請使用 `splice()` 從 `arr` 裏移除元素,使剩餘的元素之和爲 `10`。
|
||||
|
||||
# --hints--
|
||||
|
||||
不應修改這一行 `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
__helpers.removeWhiteSpace(code).match(/constarr=\[2,4,5,1,7,5,2,1\];?/)
|
||||
);
|
||||
```
|
||||
|
||||
`arr` 的剩餘元素之和應爲 `10`。
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
arr.reduce((a, b) => a + b),
|
||||
10
|
||||
);
|
||||
```
|
||||
|
||||
應對 `arr` 調用 `splice()` 方法。
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
|
||||
```
|
||||
|
||||
splice 應只刪除 `arr` 裏面的元素,不能給 `arr` 添加元素。
|
||||
|
||||
```js
|
||||
assert(
|
||||
!__helpers.removeWhiteSpace(code).match(/arr\.splice\(\d+,\d+,\d+.*\)/g)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
console.log(arr);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
|
||||
arr.splice(1, 4);
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b20
|
||||
title: 使用數組存儲不同類型的數據
|
||||
challengeType: 1
|
||||
forumTopicId: 301167
|
||||
dashedName: use-an-array-to-store-a-collection-of-data
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
以下是最簡單的數組(Array)示例: 這是一個一維數組(<dfn>one-dimensional array</dfn>),它只有一層,或者說它裏面沒有包含其它數組。 可以觀察到,這個數組中只包含了布爾值(<dfn>booleans</dfn>)、字符串(<dfn>strings</dfn>)、數字(<dfn>numbers</dfn>)以及 JavaScript 中的其他數據類型:
|
||||
|
||||
```js
|
||||
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
|
||||
console.log(simpleArray.length);
|
||||
```
|
||||
|
||||
調用 `console.log` 顯示 `7`。
|
||||
|
||||
所有數組都有一個表示長度的屬性,我們可以通過 `Array.length` 來訪問它。 下面是一個關於數組的更復雜的例子。 這是一個多維數組 (<dfn>multi-dimensional Array</dfn>),或者說是一個包含了其他數組的數組。 可以注意到,在它的內部還包含了 JavaScript 中的對象(<dfn>objects</dfn>)結構。 我們會在後面的小節中討論該數據結構,但現在你只需要知道數組能夠存儲複雜的對象類型數據。
|
||||
|
||||
```js
|
||||
let complexArray = [
|
||||
[
|
||||
{
|
||||
one: 1,
|
||||
two: 2
|
||||
},
|
||||
{
|
||||
three: 3,
|
||||
four: 4
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
a: "a",
|
||||
b: "b"
|
||||
},
|
||||
{
|
||||
c: "c",
|
||||
d: "d"
|
||||
}
|
||||
]
|
||||
];
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我們已經定義了一個名爲 `yourArray` 的變量。 請修改代碼,將一個含有至少 5 個元素的數組賦值給 `yourArray` 變量。 你的數組中應包含至少一個 <dfn>string</dfn> 類型的數據、一個 <dfn>number</dfn> 類型的數據和一個 <dfn>boolean</dfn> 類型的數據。
|
||||
|
||||
# --hints--
|
||||
|
||||
`yourArray` 應爲數組。
|
||||
|
||||
```js
|
||||
assert.strictEqual(Array.isArray(yourArray), true);
|
||||
```
|
||||
|
||||
`yourArray` 應包含至少 5 個元素。
|
||||
|
||||
```js
|
||||
assert.isAtLeast(yourArray.length, 5);
|
||||
```
|
||||
|
||||
`yourArray` 應包含至少一個 `boolean`。
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` 應包含至少一個 `number`。
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` 應包含至少一個 `string`。
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let yourArray; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let yourArray = ['a string', 100, true, ['one', 2], 'another string'];
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1b
|
||||
title: 使用 delete 關鍵字刪除對象屬性
|
||||
challengeType: 1
|
||||
forumTopicId: 301168
|
||||
dashedName: use-the-delete-keyword-to-remove-object-properties
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
現在我們已經學習了什麼是對象以及對象的基本特性和用途。 總之,對象是以鍵值對的形式,靈活、直觀地存儲結構化數據的一種方式,***而且***,通過對象的屬性查找屬性值是速度很快的操作。 在本章餘下的挑戰中,我們來了解一下對象的幾種常用操作,這樣你能更好地在代碼中使用這個十分有用的數據結構:對象。
|
||||
|
||||
在之前的挑戰中,我們已經試過添加和修改對象中的鍵值對。 現在我們來看看如何從一個對象中*移除*一個鍵值對。
|
||||
|
||||
我們再來回顧一下上一個挑戰中的 `foods` 對象。 如果我們想移除 `apples` 屬性,可以像這樣使用 `delete` 關鍵字:
|
||||
|
||||
```js
|
||||
delete foods.apples;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
請使用 delete 關鍵字來移除 `foods` 中的 `oranges`、`plums` 和 `strawberries` 屬性。
|
||||
|
||||
# --hints--
|
||||
|
||||
`foods` 對象應只包含 3 個屬性:`apples`、`grapes` 和 `bananas`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
!foods.hasOwnProperty('oranges') &&
|
||||
!foods.hasOwnProperty('plums') &&
|
||||
!foods.hasOwnProperty('strawberries') &&
|
||||
Object.keys(foods).length === 3
|
||||
);
|
||||
```
|
||||
|
||||
應使用 `delete` 關鍵字來移除 `oranges`、`plums` 和 `strawberries` 屬性。
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.search(/oranges:/) !== -1 &&
|
||||
code.search(/plums:/) !== -1 &&
|
||||
code.search(/strawberries:/) !== -1
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(foods);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
|
||||
delete foods.oranges;
|
||||
delete foods.plums;
|
||||
delete foods.strawberries;
|
||||
|
||||
console.log(foods);
|
||||
```
|
@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392ca
|
||||
title: 通過索引訪問數組中的數據
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZQbTz'
|
||||
forumTopicId: 16158
|
||||
dashedName: access-array-data-with-indexes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們可以使用索引(<dfn>indexes</dfn>)來訪問數組中的數據。
|
||||
|
||||
數組索引與字符串一樣使用方括號來表示,不同的是,它們不是指定字符,而是指定數組中的一個條目。 數組索引與字符串索引一樣是從 0 開始(<dfn>zero-based</dfn>)的,所以數組中第一個元素的索引編號是 `0`。
|
||||
|
||||
<br>
|
||||
|
||||
**示例**
|
||||
|
||||
```js
|
||||
var array = [50,60,70];
|
||||
array[0];
|
||||
var data = array[1];
|
||||
```
|
||||
|
||||
現在 `array[0]` 的值是 `50`, `data` 的值爲 `60`.
|
||||
|
||||
**注意:**數組名與方括號之間不應該有任何空格,比如`array [0]` 。 儘管 JavaScript 能夠正確處理這種情況,但是當其他程序員閱讀你寫的代碼時,這可能讓他們感到困惑。
|
||||
|
||||
# --instructions--
|
||||
|
||||
創建一個名爲 `myData` 的變量,使用方括號取出 `myArray` 數組中第一個元素的值並將其賦值給新創建的變量。
|
||||
|
||||
# --hints--
|
||||
|
||||
變量 `myData` 應該等於`myArray` 數組中第一個元素的值。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myArray !== 'undefined' &&
|
||||
typeof myData !== 'undefined' &&
|
||||
myArray[0] === myData
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
應該使用括號訪問變量 `myArray` 中的數據。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (code.match(/\s*=\s*myArray\[0\]/g)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined" && typeof myData !== "undefined"){(function(y,z){return 'myArray = ' + JSON.stringify(y) + ', myData = ' + JSON.stringify(z);})(myArray, myData);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myArray = [50,60,70];
|
||||
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [50,60,70];
|
||||
var myData = myArray[0];
|
||||
```
|
@ -0,0 +1,71 @@
|
||||
---
|
||||
id: 56592a60ddddeae28f7aa8e1
|
||||
title: 使用索引訪問多維數組
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ckND4Cq'
|
||||
forumTopicId: 16159
|
||||
dashedName: access-multi-dimensional-arrays-with-indexes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們可以把<dfn>多維</dfn>數組看作成是*數組中的數組*。 使用方括號表示法訪問數組時,第一個方括號訪問的是數組的最外層(第一層),第二個方括號訪問的是數組的第二層,以此類推。
|
||||
|
||||
**例如:**
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
[1,2,3],
|
||||
[4,5,6],
|
||||
[7,8,9],
|
||||
[[10,11,12], 13, 14]
|
||||
];
|
||||
arr[3];
|
||||
arr[3][0];
|
||||
arr[3][0][1];
|
||||
```
|
||||
|
||||
`arr[3]` 爲 `[[10, 11, 12], 13, 14]`,`arr[3][0]` 爲 `[10, 11, 12]`,並且 `arr[3][0][1]` 爲 `11`。
|
||||
|
||||
**注意:** 數組名與方括號之間不應該有任何空格,比如`array [0][0]` 甚至是 `array [0] [0]` 都是不允許的。 儘管 JavaScript 能夠正確處理這種情況,但是當其他程序員閱讀你寫的代碼時,這可能讓他們感到困惑。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用方括號從 `myArray` 中選取一個值,使得 `myData` 等於 `8`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myData` 應該等於 `8`。
|
||||
|
||||
```js
|
||||
assert(myData === 8);
|
||||
```
|
||||
|
||||
你應該使用方括號從 `myArray` 中讀取正確的值。
|
||||
|
||||
```js
|
||||
assert(/myData=myArray\[2\]\[1\]/.test(__helpers.removeWhiteSpace(code)));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return "myData: " + myData + " myArray: " + JSON.stringify(myArray);})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];
|
||||
|
||||
var myData = myArray[0][0];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];
|
||||
var myData = myArray[2][1];
|
||||
```
|
@ -0,0 +1,125 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cd
|
||||
title: 訪問嵌套數組
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
|
||||
forumTopicId: 16160
|
||||
dashedName: accessing-nested-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在之前的挑戰中,我們學習了在對象中嵌套對象和數組。 與訪問嵌套對象類似,數組的方括號可以用來對嵌套數組進行鏈式訪問。
|
||||
|
||||
下面是訪問嵌套數組的例子:
|
||||
|
||||
```js
|
||||
var ourPets = [
|
||||
{
|
||||
animalType: "cat",
|
||||
names: [
|
||||
"Meowzer",
|
||||
"Fluffy",
|
||||
"Kit-Cat"
|
||||
]
|
||||
},
|
||||
{
|
||||
animalType: "dog",
|
||||
names: [
|
||||
"Spot",
|
||||
"Bowser",
|
||||
"Frankie"
|
||||
]
|
||||
}
|
||||
];
|
||||
ourPets[0].names[1];
|
||||
ourPets[1].names[0];
|
||||
```
|
||||
|
||||
`ourPets[0].names[1]` 應該是字符串 `Fluffy`, 並且 `ourPets[1].names[0]` 應該是字符串 `Spot`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用對象的點號和數組的方括號從變量 `myPlants` 檢索出第二棵樹。
|
||||
|
||||
# --hints--
|
||||
|
||||
`secondTree` 應該等於字符串 `pine`。
|
||||
|
||||
```js
|
||||
assert(secondTree === 'pine');
|
||||
```
|
||||
|
||||
你的代碼應該使用點號和方括號訪問 `myPlants`。
|
||||
|
||||
```js
|
||||
assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(x) {
|
||||
if(typeof x != 'undefined') {
|
||||
return "secondTree = " + x;
|
||||
}
|
||||
return "secondTree is undefined";
|
||||
})(secondTree);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myPlants = [
|
||||
{
|
||||
type: "flowers",
|
||||
list: [
|
||||
"rose",
|
||||
"tulip",
|
||||
"dandelion"
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "trees",
|
||||
list: [
|
||||
"fir",
|
||||
"pine",
|
||||
"birch"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var secondTree = ""; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myPlants = [
|
||||
{
|
||||
type: "flowers",
|
||||
list: [
|
||||
"rose",
|
||||
"tulip",
|
||||
"dandelion"
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "trees",
|
||||
list: [
|
||||
"fir",
|
||||
"pine",
|
||||
"birch"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var secondTree = myPlants[1].list[1];
|
||||
```
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cc
|
||||
title: 訪問嵌套對象
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRnRnfa'
|
||||
forumTopicId: 16161
|
||||
dashedName: accessing-nested-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們可以通過連續使用點號表示法和方括號表示法來訪問對象的嵌套屬性。
|
||||
|
||||
這是一個嵌套對象:
|
||||
|
||||
```js
|
||||
var ourStorage = {
|
||||
"desk": {
|
||||
"drawer": "stapler"
|
||||
},
|
||||
"cabinet": {
|
||||
"top drawer": {
|
||||
"folder1": "a file",
|
||||
"folder2": "secrets"
|
||||
},
|
||||
"bottom drawer": "soda"
|
||||
}
|
||||
};
|
||||
ourStorage.cabinet["top drawer"].folder2;
|
||||
ourStorage.desk.drawer;
|
||||
```
|
||||
|
||||
`ourStorage.cabinet["top drawer"].folder2` 將會是字符串 `secrets`,並且 `ourStorage.desk.drawer` 將會是字符串 `stapler`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
訪問 `myStorage` 對象並將 `glove box` 屬性的內容賦值給 `gloveBoxContents` 變量。 在可能的情況下,對所有的屬性使用點號,否則使用方括號。
|
||||
|
||||
# --hints--
|
||||
|
||||
`gloveBoxContents` 應該等於字符串 `maps`。
|
||||
|
||||
```js
|
||||
assert(gloveBoxContents === 'maps');
|
||||
```
|
||||
|
||||
你的代碼應該使用點號和方括號來訪問 `myStorage`。
|
||||
|
||||
```js
|
||||
assert(/=\s*myStorage\.car\.inside\[\s*("|')glove box\1\s*\]/g.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(x) {
|
||||
if(typeof x != 'undefined') {
|
||||
return "gloveBoxContents = " + x;
|
||||
}
|
||||
return "gloveBoxContents is undefined";
|
||||
})(gloveBoxContents);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStorage = {
|
||||
"car": {
|
||||
"inside": {
|
||||
"glove box": "maps",
|
||||
"passenger seat": "crumbs"
|
||||
},
|
||||
"outside": {
|
||||
"trunk": "jack"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var gloveBoxContents = undefined;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStorage = {
|
||||
"car":{
|
||||
"inside":{
|
||||
"glove box":"maps",
|
||||
"passenger seat":"crumbs"
|
||||
},
|
||||
"outside":{
|
||||
"trunk":"jack"
|
||||
}
|
||||
}
|
||||
};
|
||||
var gloveBoxContents = myStorage.car.inside["glove box"];
|
||||
```
|
@ -0,0 +1,103 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c8
|
||||
title: 使用方括號表示法訪問對象屬性
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBvmEHP'
|
||||
forumTopicId: 16163
|
||||
dashedName: accessing-object-properties-with-bracket-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
訪問對象屬性的第二種方式是方括號表示法(`[]`)。 如果你想訪問的屬性名中包含空格,就必須使用方括號表示法來獲取它的屬性值。
|
||||
|
||||
當然,如果屬性名不包含空格,也可以使用方括號表示法。
|
||||
|
||||
這是一個使用方括號表示法讀取對象屬性的例子:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
"Space Name": "Kirk",
|
||||
"More Space": "Spock",
|
||||
"NoSpace": "USS Enterprise"
|
||||
};
|
||||
myObj["Space Name"];
|
||||
myObj['More Space'];
|
||||
myObj["NoSpace"];
|
||||
```
|
||||
|
||||
`myObj["Space Name"]` 將會是字符串 `Kirk`,`myObj['More Space']` 將會是字符串 `Spock`,並且`myObj["NoSpace"]` 將會是字符串 `USS Enterprise`。
|
||||
|
||||
注意,如果屬性名中包含空格,就必須使用引號(單引號或雙引號)將它們包裹起來。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用方括號讀取 `testObj` 中 `an entree` 和 `the drink` 的屬性值,並分別將它們賦值給 `entreeValue` 和 `drinkValue`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`entreeValue` 應該是一個字符串。
|
||||
|
||||
```js
|
||||
assert(typeof entreeValue === 'string');
|
||||
```
|
||||
|
||||
`entreeValue` 的值應該爲字符串 `hamburger`
|
||||
|
||||
```js
|
||||
assert(entreeValue === 'hamburger');
|
||||
```
|
||||
|
||||
`drinkValue` 應該是一個字符串
|
||||
|
||||
```js
|
||||
assert(typeof drinkValue === 'string');
|
||||
```
|
||||
|
||||
`drinkValue` 的值應該爲字符串 `water`
|
||||
|
||||
```js
|
||||
assert(drinkValue === 'water');
|
||||
```
|
||||
|
||||
你應該使用兩次方括號
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\s*?\[('|")[^'"]+\1\]/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b) { return "entreeValue = '" + a + "', drinkValue = '" + b + "'"; })(entreeValue,drinkValue);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
"an entree": "hamburger",
|
||||
"my side": "veggies",
|
||||
"the drink": "water"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var entreeValue = testObj; // Change this line
|
||||
var drinkValue = testObj; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
"an entree": "hamburger",
|
||||
"my side": "veggies",
|
||||
"the drink": "water"
|
||||
};
|
||||
var entreeValue = testObj["an entree"];
|
||||
var drinkValue = testObj['the drink'];
|
||||
```
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c7
|
||||
title: 通過點號表示法訪問對象屬性
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cGryJs8'
|
||||
forumTopicId: 16164
|
||||
dashedName: accessing-object-properties-with-dot-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
和訪問數組類似,訪問對象屬性有兩種方式:點號表示法(`.`)和方括號表示法(`[]`)。
|
||||
|
||||
如果我們已經提前知道要訪問的屬性名,使用點號表示法是最方便的。
|
||||
|
||||
這裏是一個用點符號(`.`)讀取對象屬性的示例:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
prop1: "val1",
|
||||
prop2: "val2"
|
||||
};
|
||||
var prop1val = myObj.prop1;
|
||||
var prop2val = myObj.prop2;
|
||||
```
|
||||
|
||||
`prop1val` 的值將爲字符串 `val1`,並且`prop2val` 的值將爲字符串 `val2`。
|
||||
# --instructions--
|
||||
|
||||
使用點號讀取 `testObj` 的屬性值。 將變量 `hatValue` 的值設置爲該對象的 `hat` 屬性的值,並將變量 `shirtValue` 的值設置爲該對象的 `shirt` 屬性的值。
|
||||
|
||||
# --hints--
|
||||
|
||||
`hatValue` 應該是一個字符串
|
||||
|
||||
```js
|
||||
assert(typeof hatValue === 'string');
|
||||
```
|
||||
|
||||
`hatValue` 的值應該爲字符串 `ballcap`
|
||||
|
||||
```js
|
||||
assert(hatValue === 'ballcap');
|
||||
```
|
||||
|
||||
`shirtValue` 應該是一個字符串
|
||||
|
||||
```js
|
||||
assert(typeof shirtValue === 'string');
|
||||
```
|
||||
|
||||
`shirtValue` 的值應該爲字符串 `jersey`
|
||||
|
||||
```js
|
||||
assert(shirtValue === 'jersey');
|
||||
```
|
||||
|
||||
你應該使用兩個點號
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\.\w+/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b) { return "hatValue = '" + a + "', shirtValue = '" + b + "'"; })(hatValue,shirtValue);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
"hat": "ballcap",
|
||||
"shirt": "jersey",
|
||||
"shoes": "cleats"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var hatValue = testObj; // Change this line
|
||||
var shirtValue = testObj; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
"hat": "ballcap",
|
||||
"shirt": "jersey",
|
||||
"shoes": "cleats"
|
||||
};
|
||||
|
||||
var hatValue = testObj.hat;
|
||||
var shirtValue = testObj.shirt;
|
||||
```
|
@ -0,0 +1,121 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c9
|
||||
title: 通過變量訪問對象屬性
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cnQyKur'
|
||||
forumTopicId: 16165
|
||||
dashedName: accessing-object-properties-with-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
對對象上使用方括號表示法,還可以訪問對象上作爲變量值存儲的屬性。 當你需要遍歷對象的所有屬性,或者根據一個變量的值查找對應的屬性值時,這種寫法尤其適用。
|
||||
|
||||
以下是一個使用變量來訪問屬性的例子:
|
||||
|
||||
```js
|
||||
var dogs = {
|
||||
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
|
||||
};
|
||||
var myDog = "Hunter";
|
||||
var myBreed = dogs[myDog];
|
||||
console.log(myBreed);
|
||||
```
|
||||
|
||||
字符串 `Doberman` 將會出現在控制檯中。
|
||||
|
||||
使用這一概念的另一種情況是:屬性的名字是在程序運行期間動態收集得到的。如下所示:
|
||||
|
||||
```js
|
||||
var someObj = {
|
||||
propName: "John"
|
||||
};
|
||||
function propPrefix(str) {
|
||||
var s = "prop";
|
||||
return s + str;
|
||||
}
|
||||
var someProp = propPrefix("Name");
|
||||
console.log(someObj[someProp]);
|
||||
```
|
||||
|
||||
`someProp` 的值將爲字符串 `propName`,並且字符串 `John` 將會出現在控制檯中。
|
||||
|
||||
注意,當使用變量名訪問屬性時,我們*沒有*使用引號包裹它,因爲我們正在使用的是變量的*值*,而不是變量的*名字*。
|
||||
|
||||
# --instructions--
|
||||
|
||||
將變量 `playerNumber` 設置爲 `16`。 然後,使用該變量查找玩家的名字,並將其賦值給`player`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`playerNumber` 應該是一個數字
|
||||
|
||||
```js
|
||||
assert(typeof playerNumber === 'number');
|
||||
```
|
||||
|
||||
變量 `player` 應該是一個字符串
|
||||
|
||||
```js
|
||||
assert(typeof player === 'string');
|
||||
```
|
||||
|
||||
`player` 的值應該爲字符串 `Montana`
|
||||
|
||||
```js
|
||||
assert(player === 'Montana');
|
||||
```
|
||||
|
||||
你應該使用方括號訪問 `testObj`
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[.*?\]/.test(code));
|
||||
```
|
||||
|
||||
你不應該直接將值 `Montana` 賦給變量 `player`。
|
||||
|
||||
```js
|
||||
assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
|
||||
```
|
||||
|
||||
你應該在你的方括號內使用變量 `playerNumber`。
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof player !== "undefined"){(function(v){return v;})(player);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
12: "Namath",
|
||||
16: "Montana",
|
||||
19: "Unitas"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var playerNumber; // Change this line
|
||||
var player = testObj; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
12: "Namath",
|
||||
16: "Montana",
|
||||
19: "Unitas"
|
||||
};
|
||||
var playerNumber = 16;
|
||||
var player = testObj[playerNumber];
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d2
|
||||
title: 給 JavaScript 對象添加新屬性
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQe38UD'
|
||||
forumTopicId: 301169
|
||||
dashedName: add-new-properties-to-a-javascript-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
你也可以像更改屬性一樣給 JavaScript 對象添加屬性。
|
||||
|
||||
這裏展示瞭如何給 `ourDog` 添加一個屬性 `bark`:
|
||||
|
||||
```js
|
||||
ourDog.bark = "bow-wow";
|
||||
```
|
||||
|
||||
或者
|
||||
|
||||
```js
|
||||
ourDog["bark"] = "bow-wow";
|
||||
```
|
||||
|
||||
現在,當我們執行 `ourDog.bark` 時,就能得到他的叫聲,`bow-wow`。
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
|
||||
ourDog.bark = "bow-wow";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
給 `myDog` 添加一個屬性 `bark` ,並將其設置爲狗的聲音,比如 “woof“。 可以使用點操作符或者中括號操作符。
|
||||
|
||||
# --hints--
|
||||
|
||||
應該給 `myDog` 添加屬性 `bark`。
|
||||
|
||||
```js
|
||||
assert(myDog.bark !== undefined);
|
||||
```
|
||||
|
||||
不應該在初始化部分添加 `bark`。
|
||||
|
||||
```js
|
||||
assert(!/bark[^\n]:/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
myDog.bark = "Woof Woof";
|
||||
```
|
@ -0,0 +1,62 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb3bdef
|
||||
title: 加法運算
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KBAG'
|
||||
forumTopicId: 16650
|
||||
dashedName: add-two-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`Number` 是 JavaScript 中的一種數據類型,用來表示數值。
|
||||
|
||||
現在我們來嘗試在 JavaScript 中做加法運算。
|
||||
|
||||
JavaScript 中,我們通過符號 `+` 來進行加法運算。
|
||||
|
||||
**代碼示例:**
|
||||
|
||||
```js
|
||||
myVar = 5 + 10;
|
||||
```
|
||||
|
||||
現在,變量 `myVar` 的值爲 `15`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
請改變數字 `0` 讓變量 sum 的值爲 `20`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`sum` 的值應該等於 `20`。
|
||||
|
||||
```js
|
||||
assert(sum === 20);
|
||||
```
|
||||
|
||||
請使用 `+` 運算符。
|
||||
|
||||
```js
|
||||
assert(/\+/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'sum = '+z;})(sum);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var sum = 10 + 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var sum = 10 + 10;
|
||||
```
|
@ -0,0 +1,128 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244de
|
||||
title: 在 switch 語句中添加默認選項
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c3JvVfg'
|
||||
forumTopicId: 16653
|
||||
dashedName: adding-a-default-option-in-switch-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在 `switch` 語句中,你可能無法用 `case` 枚舉出所有可能的值。 相反,你可以添加 `default` 語句,它會在找不到相匹配的 `case` 語句之後執行。 你可以把它看作是 `if/else` 鏈中最後的那個 `else` 語句。
|
||||
|
||||
`default` 語句應該被放到最後。
|
||||
|
||||
```js
|
||||
switch (num) {
|
||||
case value1:
|
||||
statement1;
|
||||
break;
|
||||
case value2:
|
||||
statement2;
|
||||
break;
|
||||
...
|
||||
default:
|
||||
defaultStatement;
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
寫一個 switch 語句,設置以下條件設置 `answer`:
|
||||
`a` - `apple`
|
||||
`b` - `bird`
|
||||
`c` - `cat`
|
||||
`default` - `stuff`
|
||||
|
||||
# --hints--
|
||||
|
||||
`switchOfStuff("a")` 應該返回字符串 `apple`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('a') === 'apple');
|
||||
```
|
||||
|
||||
`switchOfStuff("b")` 應該返回字符串 `bird`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('b') === 'bird');
|
||||
```
|
||||
|
||||
`switchOfStuff("c")` 應該返回字符串 `cat`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('c') === 'cat');
|
||||
```
|
||||
|
||||
`switchOfStuff("d")` 應該返回字符串 `stuff`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('d') === 'stuff');
|
||||
```
|
||||
|
||||
`switchOfStuff(4)` 應該返回字符串 `stuff`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff(4) === 'stuff');
|
||||
```
|
||||
|
||||
不能使用 `if` 或 `else` 語句。
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
你應該使用 `default` 語句。
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('string-to-trigger-default-case') === 'stuff');
|
||||
```
|
||||
|
||||
你至少應該寫 3 個 `break` 語句。
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length > 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function switchOfStuff(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
switchOfStuff(1);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function switchOfStuff(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case "a":
|
||||
answer = "apple";
|
||||
break;
|
||||
case "b":
|
||||
answer = "bird";
|
||||
break;
|
||||
case "c":
|
||||
answer = "cat";
|
||||
break;
|
||||
default:
|
||||
answer = "stuff";
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ed
|
||||
title: 將變量追加到字符串
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmZfa'
|
||||
forumTopicId: 16656
|
||||
dashedName: appending-variables-to-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
就像我們可以用多行字符串<dfn>字面量</dfn>構建單個字符串一樣,我們還可以使用加且賦值(`+=`)運算符將字符串追加到字符串的末尾。
|
||||
|
||||
示例:
|
||||
|
||||
```js
|
||||
var anAdjective = "awesome!";
|
||||
var ourStr = "freeCodeCamp is ";
|
||||
ourStr += anAdjective;
|
||||
```
|
||||
|
||||
`ourStr` 值爲 `freeCodeCamp is awesome!`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
將 `someAdjective` 設置爲一個至少包含 3 個字符的字符串,然後使用 `+=` 運算符將它追加到 `myStr`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`someAdjective` 應當爲包含至少三個字符的字符串。
|
||||
|
||||
```js
|
||||
assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2);
|
||||
```
|
||||
|
||||
你應該使用 `+=` 運算符將 `someAdjective` 追加到 `myStr`。
|
||||
|
||||
```js
|
||||
assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
var output = [];
|
||||
if(typeof someAdjective === 'string') {
|
||||
output.push('someAdjective = "' + someAdjective + '"');
|
||||
} else {
|
||||
output.push('someAdjective is not a string');
|
||||
}
|
||||
if(typeof myStr === 'string') {
|
||||
output.push('myStr = "' + myStr + '"');
|
||||
} else {
|
||||
output.push('myStr is not a string');
|
||||
}
|
||||
return output.join('\n');
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Change code below this line
|
||||
|
||||
var someAdjective;
|
||||
var myStr = "Learning to code is ";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var someAdjective = "neat";
|
||||
var myStr = "Learning to code is ";
|
||||
myStr += someAdjective;
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 5ee127a03c3b35dd45426493
|
||||
title: 將一個變量的值賦給另一個
|
||||
challengeType: 1
|
||||
videoUrl: ''
|
||||
forumTopicId: 418265
|
||||
dashedName: assigning-the-value-of-one-variable-to-another
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在使用<dfn>賦值</dfn>運算符賦予變量某個值後,你可以使用<dfn>賦值</dfn>運算符將該變量的值賦給另一個變量。
|
||||
|
||||
```js
|
||||
var myVar;
|
||||
myVar = 5;
|
||||
var myNum;
|
||||
myNum = myVar;
|
||||
```
|
||||
|
||||
以上代碼聲明瞭一個沒有初始值的變量 `myVar`,然後給它賦值爲 `5`。 緊接着,又聲明瞭一個沒有初始值的變量 `myNum`。 然後,變量 `myVar` 的內容(也就是 `5`)被賦給了變量 `myNum`。 現在,變量 `myNum` 的值也爲 `5`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
把變量 `a` 的內容賦給變量 `b`。
|
||||
|
||||
# --hints--
|
||||
|
||||
你不應該修改註釋上面的代碼。
|
||||
|
||||
```js
|
||||
assert(/var a;/.test(code) && /a = 7;/.test(code) && /var b;/.test(code));
|
||||
```
|
||||
|
||||
`b` 的值應該爲 `7`。
|
||||
|
||||
```js
|
||||
assert(typeof b === 'number' && b === 7);
|
||||
```
|
||||
|
||||
應該使用 `=` 將 `a` 賦給 `b`。
|
||||
|
||||
```js
|
||||
assert(/b\s*=\s*a\s*/g.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
if (typeof a != 'undefined') {
|
||||
a = undefined;
|
||||
}
|
||||
if (typeof b != 'undefined') {
|
||||
b = undefined;
|
||||
}
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a, b) {
|
||||
return 'a = ' + a + ', b = ' + b;
|
||||
})(a, b);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var a;
|
||||
a = 7;
|
||||
var b;
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a;
|
||||
a = 7;
|
||||
var b;
|
||||
b = a;
|
||||
```
|
@ -0,0 +1,71 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c3
|
||||
title: 使用返回值賦值
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2pEtB'
|
||||
forumTopicId: 16658
|
||||
dashedName: assignment-with-a-returned-value
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
如果你還記得我們在[使用賦值運算符存儲值](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator)中的討論的話,等號右側的所有操作都會在賦值之前完成。 這意味着我們可以獲取函數的返回值,並將其賦值給一個變量。
|
||||
|
||||
假設我們有一個預先定義的函數 `sum` ,它將兩個數相加,然後:
|
||||
|
||||
```js
|
||||
ourSum = sum(5, 12);
|
||||
```
|
||||
|
||||
將會調用函數 `sum`,函數返回值 `17`,然後將該值賦給變量 `ourSum`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
調用 `processArg` 函數,參數爲 `7`,然後把返回的值賦值給變量 `processed`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`processed` 的值應爲 `2`。
|
||||
|
||||
```js
|
||||
assert(processed === 2);
|
||||
```
|
||||
|
||||
應該將 `processArg` 賦值給 `processed`。
|
||||
|
||||
```js
|
||||
assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){return "processed = " + processed})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
processed = processArg(7);
|
||||
```
|
@ -0,0 +1,159 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d0
|
||||
title: 創建 JavaScript 對象
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWGkbtd'
|
||||
forumTopicId: 16769
|
||||
dashedName: build-javascript-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
你之前可能聽過 `object` 這個詞。
|
||||
|
||||
對象和 `arrays` 類似,區別在於數組使用索引來訪問和修改數據,而對象中的數據是通過 `properties` 訪問的。
|
||||
|
||||
對象非常適合用來存儲結構化數據,可以表示真實世界中的物體,比如一隻貓。
|
||||
|
||||
這裏是一個貓對象的樣本:
|
||||
|
||||
```js
|
||||
var cat = {
|
||||
"name": "Whiskers",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"enemies": ["Water", "Dogs"]
|
||||
};
|
||||
```
|
||||
|
||||
在這個示例中,所有的屬性都被純屬爲字符串,比如 `name`、`legs` 和 `tails`。 然而,你也可以使用數字作爲屬性。 你甚至可以省略單字字符串屬性中的引號,如下所示:
|
||||
|
||||
```js
|
||||
var anotherObject = {
|
||||
make: "Ford",
|
||||
5: "five",
|
||||
"model": "focus"
|
||||
};
|
||||
```
|
||||
|
||||
然而,如果你的對象有非字符串屬性的話,JavaScript 會自動將它們轉爲字符串。
|
||||
|
||||
# --instructions--
|
||||
|
||||
確保對象表示一隻名爲 `myDog` 的狗,包含屬性 `name`(字符串)、`legs`、`tails` 和 `friends`。
|
||||
|
||||
你可以隨意設置這些對象的屬性值,只要 `name` 是字符串,`legs` 和 `tails` 是數字,`friends` 是數組即可。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDog` 應該包含 `name` 屬性,並且它應該是一個 `string`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('name') &&
|
||||
z.name !== undefined &&
|
||||
typeof z.name === 'string'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog`應該包含 `legs` 屬性,並且它應該是一個 `number`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('legs') &&
|
||||
z.legs !== undefined &&
|
||||
typeof z.legs === 'number'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` 應該包含 `tails` 屬性,並且它應該是一個 `number`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('tails') &&
|
||||
z.tails !== undefined &&
|
||||
typeof z.tails === 'number'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` 應該包含 `friends` 屬性,並且它應該是一個 `array`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('friends') &&
|
||||
z.friends !== undefined &&
|
||||
Array.isArray(z.friends)
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` 只應該包含所有給定的屬性。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
return Object.keys(z).length === 4;
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
};
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
```
|
@ -0,0 +1,149 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244dc
|
||||
title: 多個 if else 語句
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJgsw'
|
||||
forumTopicId: 16772
|
||||
dashedName: chaining-if-else-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`if/else` 語句串聯在一起可以實現複雜的邏輯。 這是多個 `if` / `else if` 語句串聯在一起的<dfn>僞代碼</dfn>:
|
||||
|
||||
```js
|
||||
if (condition1) {
|
||||
statement1
|
||||
} else if (condition2) {
|
||||
statement2
|
||||
} else if (condition3) {
|
||||
statement3
|
||||
. . .
|
||||
} else {
|
||||
statementN
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
請將 `if`/`else if` 語句串聯起來,實現下面的邏輯:
|
||||
|
||||
`num < 5` - 返回 `Tiny`
|
||||
`num < 10` - 返回 `Small`
|
||||
`num < 15` - 返回 `Medium`
|
||||
`num < 20` - 返回 `Large`
|
||||
`num >= 20` - 返回 `Huge`
|
||||
|
||||
# --hints--
|
||||
|
||||
應至少有 4 個 `else` 語句。
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 3);
|
||||
```
|
||||
|
||||
應至少有 4 個 `if` 語句。
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 3);
|
||||
```
|
||||
|
||||
應至少有 1 個 `return` 語句。
|
||||
|
||||
```js
|
||||
assert(code.match(/return/g).length >= 1);
|
||||
```
|
||||
|
||||
`testSize(0)` 應該返回字符串 `Tiny`
|
||||
|
||||
```js
|
||||
assert(testSize(0) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(4)` 應該返回字符串 `Tiny`
|
||||
|
||||
```js
|
||||
assert(testSize(4) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(5)` 應該返回字符串 `Small`
|
||||
|
||||
```js
|
||||
assert(testSize(5) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(8)` 應該返回字符串 `Small`
|
||||
|
||||
```js
|
||||
assert(testSize(8) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(10)` 應該返回字符串 `Medium`
|
||||
|
||||
```js
|
||||
assert(testSize(10) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(14)` 應該返回字符串 `Medium`
|
||||
|
||||
```js
|
||||
assert(testSize(14) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(15)` 應該返回字符串 `Large`
|
||||
|
||||
```js
|
||||
assert(testSize(15) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(17)` 應該返回字符串 `Large`
|
||||
|
||||
```js
|
||||
assert(testSize(17) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(20)` 應該返回字符串 `Huge`
|
||||
|
||||
```js
|
||||
assert(testSize(20) === 'Huge');
|
||||
```
|
||||
|
||||
`testSize(25)` 應該返回字符串 `Huge`
|
||||
|
||||
```js
|
||||
assert(testSize(25) === 'Huge');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testSize(num) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
testSize(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testSize(num) {
|
||||
if (num < 5) {
|
||||
return "Tiny";
|
||||
} else if (num < 10) {
|
||||
return "Small";
|
||||
} else if (num < 15) {
|
||||
return "Medium";
|
||||
} else if (num < 20) {
|
||||
return "Large";
|
||||
} else {
|
||||
return "Huge";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: bd7123c9c441eddfaeb4bdef
|
||||
title: 給代碼添加註釋
|
||||
challengeType: 1
|
||||
removeComments: false
|
||||
videoUrl: 'https://scrimba.com/c/c7ynnTp'
|
||||
forumTopicId: 16783
|
||||
dashedName: comment-your-javascript-code
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
被註釋的代碼塊在 JavaScript 之中是不會執行的。 在代碼中寫註釋,是一個可以讓你自己和以後的其他人理解代碼作用的好方法。
|
||||
|
||||
JavaScript有兩種寫註釋的方法。
|
||||
|
||||
使用 `//` 註釋掉當前行的代碼。 這是一個行內註釋:
|
||||
|
||||
```js
|
||||
// This is an in-line comment.
|
||||
```
|
||||
|
||||
你也可以使用多行註釋來註釋你的代碼,使用 `/*` 開始, `*/` 結束. 這是一個多行註釋:
|
||||
|
||||
```js
|
||||
/* This is a
|
||||
multi-line comment */
|
||||
```
|
||||
|
||||
**最佳實踐**當你寫代碼的時候,你應該時不時的添加註釋來解釋你寫的代碼的作用。 適當的註釋能讓別人*和*你未來的自己更容易看懂代碼。
|
||||
|
||||
# --instructions--
|
||||
|
||||
嘗試創建這兩種類型的註釋。
|
||||
|
||||
# --hints--
|
||||
|
||||
創建一個 `//` 樣式的註釋,被註釋的文本至少要包含 5 個字符。
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\/)...../g));
|
||||
```
|
||||
|
||||
創建一個 `/* */` 樣式的註釋,被註釋的文本至少要包含 5 個字符。
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// Fake Comment
|
||||
/* Another Comment */
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d0
|
||||
title: 相等運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKyVMAL'
|
||||
forumTopicId: 16784
|
||||
dashedName: comparison-with-the-equality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在 JavaScript 中,有很多 <dfn>相互比較的操作</dfn>。 所有這些操作符都返回一個 `true` 或 `false` 值。
|
||||
|
||||
最基本的運算符是相等運算符:`==`。 相等運算符比較兩個值,如果它們是相等,返回 `true`,如果它們不相等,返回 `false`。 值得注意的是相等運算符不同於賦值運算符(`=`),賦值運算符是把等號右邊的值賦給左邊的變量。
|
||||
|
||||
```js
|
||||
function equalityTest(myVal) {
|
||||
if (myVal == 10) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
||||
|
||||
如果 `myVal` 等於 `10`,相等運算符會返回 `true`,因此大括號裏面的代碼會被執行,函數將返回 `Equal`。 否則,函數返回 `Not Equal`。 在 JavaScript 中,爲了讓兩個不同的<dfn>數據類型</dfn>(例如 `numbers` 和 `strings`)的值可以作比較,它必須把一種類型轉換爲另一種類型。 這叫作 “類型強制轉換”。 轉換之後,可以像下面這樣來比較:
|
||||
|
||||
```js
|
||||
1 == 1
|
||||
1 == 2
|
||||
1 == '1'
|
||||
"3" == 3
|
||||
```
|
||||
|
||||
按順序,這些表達式會返回 `true`、`false`、`true`、`true`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
把相等運算符添加到指定的行,這樣當 `val` 的值爲 `12` 的時候,函數會返回 `Equal`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`testEqual(10)` 應該返回字符串 `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testEqual(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testEqual(12)` 應該返回字符串 `Equal`
|
||||
|
||||
```js
|
||||
assert(testEqual(12) === 'Equal');
|
||||
```
|
||||
|
||||
`testEqual("12")` 應該返回字符串 `Equal`
|
||||
|
||||
```js
|
||||
assert(testEqual('12') === 'Equal');
|
||||
```
|
||||
|
||||
應該使用 `==` 運算符。
|
||||
|
||||
```js
|
||||
assert(code.match(/==/g) && !code.match(/===/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
testEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testEqual(val) {
|
||||
if (val == 12) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,113 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d4
|
||||
title: 大於運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cp6GbH4'
|
||||
forumTopicId: 16786
|
||||
dashedName: comparison-with-the-greater-than-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
使用大於運算符(`>`)來比較兩個數字。 如果大於運算符左邊的數字大於右邊的數字,將會返回 `true`。 否則,它返回 `false`。
|
||||
|
||||
與相等運算符一樣,大於運算符在比較的時候,會轉換值的數據類型。
|
||||
|
||||
**例如:**
|
||||
|
||||
```js
|
||||
5 > 3
|
||||
7 > '3'
|
||||
2 > 3
|
||||
'1' > 9
|
||||
```
|
||||
|
||||
按順序,這些表達式會返回 `true`、`true`、`false` 和 `false`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
添加大於運算符到指定的行,使得返回的語句是有意義的。
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterThan(0)` 應該返回字符串 `10 or Under`。
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(0) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(10)` 應該返回字符串 `10 or Under`。
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(10) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(11)` 應該返回字符串 `Over 10`。
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(11) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(99)` 應該返回字符串 `Over 10`。
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(99) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(100)` 應該返回字符串 `Over 10`。
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(100) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(101)` 應該返回字符串 `Over 100`。
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(101) === 'Over 100');
|
||||
```
|
||||
|
||||
`testGreaterThan(150)` 應該返回字符串 `Over 100`。
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(150) === 'Over 100');
|
||||
```
|
||||
|
||||
應該使用 `>` 運算符至少兩次。
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testGreaterThan(val) {
|
||||
if (val) { // Change this line
|
||||
return "Over 100";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Over 10";
|
||||
}
|
||||
|
||||
return "10 or Under";
|
||||
}
|
||||
|
||||
testGreaterThan(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testGreaterThan(val) {
|
||||
if (val > 100) { // Change this line
|
||||
return "Over 100";
|
||||
}
|
||||
if (val > 10) { // Change this line
|
||||
return "Over 10";
|
||||
}
|
||||
return "10 or Under";
|
||||
}
|
||||
```
|
@ -0,0 +1,115 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d5
|
||||
title: 大於或等於運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KBqtV'
|
||||
forumTopicId: 16785
|
||||
dashedName: comparison-with-the-greater-than-or-equal-to-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
使用大於等於運算符(`>=`)來比較兩個數字的大小。 如果大於等於運算符左邊的數字比右邊的數字大或者相等,會返回 `true`。 否則,會返回 `false`。
|
||||
|
||||
與相等運算符相似,大於等於運算符在比較的時候會轉換值的數據類型。
|
||||
|
||||
**例如:**
|
||||
|
||||
```js
|
||||
6 >= 6
|
||||
7 >= '3'
|
||||
2 >= 3
|
||||
'7' >= 9
|
||||
```
|
||||
|
||||
按順序,這些表達式會返回 `true`、`true`、`false` 和 `false`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
添加大於等於運算符到指定行,使得函數的返回語句有意義。
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterOrEqual(0)` 應該返回字符串 `Less than 10`。
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(0) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(9)` 應該返回字符串 `Less than 10`。
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(9) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(10)` 應該返回字符串 `10 or Over`。
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(10) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(11)` 應該返回字符串 `10 or Over`。
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(11) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(19)` 應該返回字符串 `10 or Over`。
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(19) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(100)` 應該返回字符串 `20 or Over`。
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(100) === '20 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(21)` 應該返回字符串 `20 or Over`。
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(21) === '20 or Over');
|
||||
```
|
||||
|
||||
應該使用 `>=` 運算符至少兩次。
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>=\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testGreaterOrEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "20 or Over";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "10 or Over";
|
||||
}
|
||||
|
||||
return "Less than 10";
|
||||
}
|
||||
|
||||
testGreaterOrEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testGreaterOrEqual(val) {
|
||||
if (val >= 20) { // Change this line
|
||||
return "20 or Over";
|
||||
}
|
||||
|
||||
if (val >= 10) { // Change this line
|
||||
return "10 or Over";
|
||||
}
|
||||
|
||||
return "Less than 10";
|
||||
}
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d2
|
||||
title: 不等運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cdBm9Sr'
|
||||
forumTopicId: 16787
|
||||
dashedName: comparison-with-the-inequality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
不相等運算符(`!=`)與相等運算符是相反的。 這意味着嚴格不相等並返回 `false` 的地方,用嚴格相等運算符會返回 `true`,*反之亦然*。 與相等運算符類似,不相等運算符在比較的時候也會轉換值的數據類型。
|
||||
|
||||
**例如**
|
||||
|
||||
```js
|
||||
1 != 2
|
||||
1 != "1"
|
||||
1 != '1'
|
||||
1 != true
|
||||
0 != false
|
||||
```
|
||||
|
||||
按順序,這些表達式會返回 `true`、`false`、`false`、`false` 和 `false`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
在 `if` 語句中,添加不相等運算符 `!=`,這樣函數在當 `val` 不等於 `99` 的時候,會返回 `Not Equal`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`testNotEqual(99)` 應該返回字符串 `Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual(99) === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("99")` 應該返回字符串 `Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual('99') === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual(12)` 應該返回字符串 `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("12")` 應該返回字符串 `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual('12') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("bob")` 應該返回字符串 `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
你應該使用 `!=` 運算符。
|
||||
|
||||
```js
|
||||
assert(code.match(/(?!!==)!=/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testNotEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
|
||||
testNotEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testNotEqual(val) {
|
||||
if (val != 99) {
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,108 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d6
|
||||
title: 小於運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVRWtB'
|
||||
forumTopicId: 16789
|
||||
dashedName: comparison-with-the-less-than-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
使用小於運算符(`<`)來比較兩個數字。 如果小於運算符左邊的數字比右邊的數字小,它會返回 `true`。 否則會返回 `false`。 與相等運算符類似,小於運算符在做比較的時候會轉換值的數據類型。
|
||||
|
||||
**例如:**
|
||||
|
||||
```js
|
||||
2 < 5
|
||||
'3' < 7
|
||||
5 < 5
|
||||
3 < 2
|
||||
'8' < 4
|
||||
```
|
||||
|
||||
按順序,這些表達式會返回 `true`、`true`、`false`、`false` 和 `false`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
添加小於運算符到指定行,使得函數的返回語句有意義。
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessThan(0)` 應該返回字符串 `Under 25`。
|
||||
|
||||
```js
|
||||
assert(testLessThan(0) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(24)` 應該返回字符串 `Under 25`。
|
||||
|
||||
```js
|
||||
assert(testLessThan(24) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(25)` 應該返回字符串 `Under 55`。
|
||||
|
||||
```js
|
||||
assert(testLessThan(25) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(54)` 應該返回字符串 `Under 55`。
|
||||
|
||||
```js
|
||||
assert(testLessThan(54) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(55)` 應該返回字符串 `55 or Over`。
|
||||
|
||||
```js
|
||||
assert(testLessThan(55) === '55 or Over');
|
||||
```
|
||||
|
||||
`testLessThan(99)` 應該返回字符串 `55 or Over`。
|
||||
|
||||
```js
|
||||
assert(testLessThan(99) === '55 or Over');
|
||||
```
|
||||
|
||||
應該使用 `<` 運算符至少兩次。
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLessThan(val) {
|
||||
if (val) { // Change this line
|
||||
return "Under 25";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Under 55";
|
||||
}
|
||||
|
||||
return "55 or Over";
|
||||
}
|
||||
|
||||
testLessThan(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLessThan(val) {
|
||||
if (val < 25) { // Change this line
|
||||
return "Under 25";
|
||||
}
|
||||
|
||||
if (val < 55) { // Change this line
|
||||
return "Under 55";
|
||||
}
|
||||
|
||||
return "55 or Over";
|
||||
}
|
||||
```
|
@ -0,0 +1,114 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d7
|
||||
title: 小於或等於運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVR7Am'
|
||||
forumTopicId: 16788
|
||||
dashedName: comparison-with-the-less-than-or-equal-to-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
使用小於等於運算符(`<=`)比較兩個數字的大小。 如果在小於等於運算符左邊的數字小於或者等於右邊的數字,它會返回 `true`。 如果在小於等於運算符左邊的數字大於右邊的數字,它會返回 `false`。 與相等運算符類似,小於或等於運算符會轉換數據類型。
|
||||
|
||||
**例如**
|
||||
|
||||
```js
|
||||
4 <= 5
|
||||
'7' <= 7
|
||||
5 <= 5
|
||||
3 <= 2
|
||||
'8' <= 4
|
||||
```
|
||||
|
||||
按順序,這些表達式會返回 `true`、`true`、`true`、`false` 和 `false`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
添加小於等於運算符到指定行,使得函數的返回語句有意義。
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessOrEqual(0)` 應該返回 `Smaller Than or Equal to 12`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(0) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(11)` 應該返回 `Smaller Than or Equal to 12`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(11) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(12)` 應該返回 `Smaller Than or Equal to 12`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(12) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(23)` 應該返回 `Smaller Than or Equal to 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(23) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(24)` 應該返回 `Smaller Than or Equal to 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(24) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(25)` 應該返回 `More Than 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(25) === 'More Than 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(55)` 應該返回 `More Than 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(55) === 'More Than 24');
|
||||
```
|
||||
|
||||
應該使用 `<=` 運算符至少兩次
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<=\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLessOrEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Smaller Than or Equal to 12";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Smaller Than or Equal to 24";
|
||||
}
|
||||
|
||||
return "More Than 24";
|
||||
}
|
||||
|
||||
testLessOrEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLessOrEqual(val) {
|
||||
if (val <= 12) { // Change this line
|
||||
return "Smaller Than or Equal to 12";
|
||||
}
|
||||
|
||||
if (val <= 24) { // Change this line
|
||||
return "Smaller Than or Equal to 24";
|
||||
}
|
||||
|
||||
return "More Than 24";
|
||||
}
|
||||
```
|
@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d1
|
||||
title: 嚴格相等運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy87atr'
|
||||
forumTopicId: 16790
|
||||
dashedName: comparison-with-the-strict-equality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
嚴格相等運算符(`===`)是相對相等操作符(`==`)的另一種比較操作符。 與相等操作符轉換數據兩類型不同,嚴格相等運算符不會做類型轉換。
|
||||
|
||||
如果比較的值類型不同,那麼在嚴格相等運算符比較下它們是不相等的,會返回 false 。
|
||||
|
||||
**示例**
|
||||
|
||||
```js
|
||||
3 === 3
|
||||
3 === '3'
|
||||
```
|
||||
|
||||
這些條件將分別返回 `true` and `false`。
|
||||
|
||||
在第二個例子中,`3` 是一個 `Number` 類型,而 `'3'` 是一個 `String` 類型。
|
||||
|
||||
# --instructions--
|
||||
|
||||
在 `if` 語句中,添加不相等運算符,這樣函數在當 `val` 嚴格等於 `7` 的時候,會返回 `Equal`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrict(10)` 應該返回字符串 `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrict(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrict(7)` 應該返回字符串 `Equal`
|
||||
|
||||
```js
|
||||
assert(testStrict(7) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrict("7")` 應該返回字符串 `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrict('7') === 'Not Equal');
|
||||
```
|
||||
|
||||
你應該使用 `===` 運算符。
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testStrict(val) {
|
||||
if (val) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
testStrict(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testStrict(val) {
|
||||
if (val === 7) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,85 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d3
|
||||
title: 嚴格不等運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKekkUy'
|
||||
forumTopicId: 16791
|
||||
dashedName: comparison-with-the-strict-inequality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
嚴格不相等運算符(`!==`)與全等運算符是相反的。 這意味着嚴格不相等並返回 `false` 的地方,用嚴格相等運算符會返回 `true`,*反之亦然*。 嚴格不相等運算符不會轉換值的數據類型。
|
||||
|
||||
**示例**
|
||||
|
||||
```js
|
||||
3 !== 3
|
||||
3 !== '3'
|
||||
4 !== 3
|
||||
```
|
||||
|
||||
按順序,這些表達式會返回 `false`、`true`、`true`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
在 `if` 語句中,添加嚴格不相等運算符,這樣函數在當 `val` 不嚴格等於 `17` 的時候,會返回 `Not Equal`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrictNotEqual(17)` 應該返回字符串 `Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(17) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("17")` 應該返回字符串 `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('17') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual(12)` 應該返回字符串 `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("bob")` 應該返回字符串 `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
應該使用 `!==` 運算符。
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testStrictNotEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
|
||||
testStrictNotEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testStrictNotEqual(val) {
|
||||
if (val !== 17) {
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,130 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d8
|
||||
title: 邏輯與運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvbRVtr'
|
||||
forumTopicId: 16799
|
||||
dashedName: comparisons-with-the-logical-and-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
有時你需要在一次判斷中做多個操作。 當且僅當<dfn>運算符</dfn>的左邊和右邊都是 true,<dfn>邏輯與</dfn>運算符(`&&`)纔會返回`true`。
|
||||
|
||||
同樣的效果可以通過 if 語句的嵌套來實現:
|
||||
|
||||
```js
|
||||
if (num > 5) {
|
||||
if (num < 10) {
|
||||
return "Yes";
|
||||
}
|
||||
}
|
||||
return "No";
|
||||
```
|
||||
|
||||
只有當 `num` 的值大於 `5` 並且小於`10` 時纔會返回 `Yes`。 相同的邏輯可被寫爲:
|
||||
|
||||
```js
|
||||
if (num > 5 && num < 10) {
|
||||
return "Yes";
|
||||
}
|
||||
return "No";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
請使用 `&&` 運算符把兩個 if 語句合併爲一個 if 語句,如果 `val` 小於或等於`50` 並且大於或等於 `25` 時,返回 `Yes`。 否則,將返回`No`。
|
||||
|
||||
# --hints--
|
||||
|
||||
你應該使用 `&&` 運算符一次。
|
||||
|
||||
```js
|
||||
assert(code.match(/&&/g).length === 1);
|
||||
```
|
||||
|
||||
你應該只有一個 `if` 表達式。
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalAnd(0)` 應該返回字符串 `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(0) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(24)` 應該返回字符串 `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(24) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(25)` 應該返回字符串 `Yes`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(25) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(30)` 應該返回字符串 `Yes`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(30) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(50)` 應該返回字符串 `Yes`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(50) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(51)` 應該返回字符串 `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(51) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(75)` 應該返回字符串 `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(75) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(80)` 應該返回字符串 `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(80) === 'No');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLogicalAnd(val) {
|
||||
// Only change code below this line
|
||||
|
||||
if (val) {
|
||||
if (val) {
|
||||
return "Yes";
|
||||
}
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return "No";
|
||||
}
|
||||
|
||||
testLogicalAnd(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLogicalAnd(val) {
|
||||
if (val >= 25 && val <= 50) {
|
||||
return "Yes";
|
||||
}
|
||||
return "No";
|
||||
}
|
||||
```
|
@ -0,0 +1,135 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d9
|
||||
title: 邏輯或運算符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cEPrGTN'
|
||||
forumTopicId: 16800
|
||||
dashedName: comparisons-with-the-logical-or-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
只要<dfn>邏輯或</dfn>運算符(`||`)兩邊的任何一個<dfn>運算</dfn>的結果是 `true`,則返回 `true`。 否則,返回 `false`。
|
||||
|
||||
<dfn>邏輯或</dfn>運算符由兩個豎線(`||`)組成。 這個按鍵位於退格鍵和回車鍵之間。
|
||||
|
||||
下面這樣的語句你應該很熟悉:
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
return "No";
|
||||
}
|
||||
if (num < 5) {
|
||||
return "No";
|
||||
}
|
||||
return "Yes";
|
||||
```
|
||||
|
||||
只有當 `num` 大於等於 `5` 或小於等於 `10` 時,函數才返回 `Yes`。 相同的邏輯可以簡寫成:
|
||||
|
||||
```js
|
||||
if (num > 10 || num < 5) {
|
||||
return "No";
|
||||
}
|
||||
return "Yes";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
請使用邏輯或運算符把兩個 `if` 語句合併爲一個語句,如果 `val` 不在 `10` 和 `20` 之間(包括 10 和 20),返回 `Outside`。 否則,返回 `Inside`。
|
||||
|
||||
# --hints--
|
||||
|
||||
應該使用一次 `||` 操作符。
|
||||
|
||||
```js
|
||||
assert(code.match(/\|\|/g).length === 1);
|
||||
```
|
||||
|
||||
應該只有一個 `if` 表達式。
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalOr(0)` 應該返回字符串 `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(0) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(9)` 應該返回字符串 `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(9) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(10)` 應該返回字符串 `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(10) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(15)` 應該返回字符串 `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(15) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(19)` 應該返回字符串 `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(19) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(20)` 應該返回字符串 `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(20) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(21)` 應該返回字符串 `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(21) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(25)` 應該返回字符串 `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(25) === 'Outside');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLogicalOr(val) {
|
||||
// Only change code below this line
|
||||
|
||||
if (val) {
|
||||
return "Outside";
|
||||
}
|
||||
|
||||
if (val) {
|
||||
return "Outside";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return "Inside";
|
||||
}
|
||||
|
||||
testLogicalOr(15);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLogicalOr(val) {
|
||||
if (val < 10 || val > 20) {
|
||||
return "Outside";
|
||||
}
|
||||
return "Inside";
|
||||
}
|
||||
```
|
@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244af
|
||||
title: 複合賦值之 +=
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDR6LCb'
|
||||
forumTopicId: 16661
|
||||
dashedName: compound-assignment-with-augmented-addition
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在編程中,通常通過賦值來修改變量的內容。 記住,賦值時 JavaScript 會先計算等號右邊的內容,所以我們可以寫這樣的語句:
|
||||
|
||||
```js
|
||||
myVar = myVar + 5;
|
||||
```
|
||||
|
||||
給 `myVar` 加上 `5`。 這是最常見的運算賦值語句,即先運算、再賦值。還有一類操作符是一步到位,既做運算也賦值的。
|
||||
|
||||
其中一種就是 `+=` 運算符。
|
||||
|
||||
```js
|
||||
var myVar = 1;
|
||||
myVar += 5;
|
||||
console.log(myVar);
|
||||
```
|
||||
|
||||
控制檯將會顯示 `6`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `+=` 操作符對 `a`、`b` 和 `c` 賦值。
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` 應該等於 `15`。
|
||||
|
||||
```js
|
||||
assert(a === 15);
|
||||
```
|
||||
|
||||
`b` 應該等於 `26`。
|
||||
|
||||
```js
|
||||
assert(b === 26);
|
||||
```
|
||||
|
||||
`c` 應該等於 `19`。
|
||||
|
||||
```js
|
||||
assert(c === 19);
|
||||
```
|
||||
|
||||
應該對每個變量使用 `+=` 操作符。
|
||||
|
||||
```js
|
||||
assert(code.match(/\+=/g).length === 3);
|
||||
```
|
||||
|
||||
不要修改註釋上面的代碼。
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 3;/.test(code) &&
|
||||
/var b = 17;/.test(code) &&
|
||||
/var c = 12;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 3;
|
||||
var b = 17;
|
||||
var c = 12;
|
||||
|
||||
// Only change code below this line
|
||||
a = a + 12;
|
||||
b = 9 + b;
|
||||
c = c + 7;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 3;
|
||||
var b = 17;
|
||||
var c = 12;
|
||||
|
||||
a += 12;
|
||||
b += 9;
|
||||
c += 7;
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b2
|
||||
title: 複合賦值之 /=
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvKT2'
|
||||
forumTopicId: 16659
|
||||
dashedName: compound-assignment-with-augmented-division
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`/=` 操作符是讓變量與另一個數相除並賦值。
|
||||
|
||||
```js
|
||||
myVar = myVar / 5;
|
||||
```
|
||||
|
||||
將 `myVar` 除以 `5`。 等價於:
|
||||
|
||||
```js
|
||||
myVar /= 5;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `/=` 操作符對 `a`,`b` 和 `c` 實現相除賦值操作。
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` 應該等於 `4`。
|
||||
|
||||
```js
|
||||
assert(a === 4);
|
||||
```
|
||||
|
||||
`b` 應該等於 `27`。
|
||||
|
||||
```js
|
||||
assert(b === 27);
|
||||
```
|
||||
|
||||
`c` 應該等於`3`。
|
||||
|
||||
```js
|
||||
assert(c === 3);
|
||||
```
|
||||
|
||||
應該對每個變量使用 `/=` 操作符。
|
||||
|
||||
```js
|
||||
assert(code.match(/\/=/g).length === 3);
|
||||
```
|
||||
|
||||
不要修改註釋上面的代碼。
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 48;/.test(code) &&
|
||||
/var b = 108;/.test(code) &&
|
||||
/var c = 33;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 48;
|
||||
var b = 108;
|
||||
var c = 33;
|
||||
|
||||
// Only change code below this line
|
||||
a = a / 12;
|
||||
b = b / 4;
|
||||
c = c / 11;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 48;
|
||||
var b = 108;
|
||||
var c = 33;
|
||||
|
||||
a /= 12;
|
||||
b /= 4;
|
||||
c /= 11;
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b1
|
||||
title: 複合賦值之 *=
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c83vrfa'
|
||||
forumTopicId: 16662
|
||||
dashedName: compound-assignment-with-augmented-multiplication
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`*=` 操作符是讓變量與一個數相乘並賦值。
|
||||
|
||||
```js
|
||||
myVar = myVar * 5;
|
||||
```
|
||||
|
||||
將 `myVar` 乘以 `5`。 等價於:
|
||||
|
||||
```js
|
||||
myVar *= 5;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `*=` 操作符對 `a`、`b` 和 `c` 實現賦值相乘操作。
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` 應該等於`25`。
|
||||
|
||||
```js
|
||||
assert(a === 25);
|
||||
```
|
||||
|
||||
`b` 應該等於`36`。
|
||||
|
||||
```js
|
||||
assert(b === 36);
|
||||
```
|
||||
|
||||
`c` 應該等於`46`。
|
||||
|
||||
```js
|
||||
assert(c === 46);
|
||||
```
|
||||
|
||||
應該對每個變量使用 `*=` 操作符。
|
||||
|
||||
```js
|
||||
assert(code.match(/\*=/g).length === 3);
|
||||
```
|
||||
|
||||
不要修改註釋上面的代碼。
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 5;/.test(code) &&
|
||||
/var b = 12;/.test(code) &&
|
||||
/var c = 4\.6;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 12;
|
||||
var c = 4.6;
|
||||
|
||||
// Only change code below this line
|
||||
a = a * 5;
|
||||
b = 3 * b;
|
||||
c = c * 10;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 12;
|
||||
var c = 4.6;
|
||||
|
||||
a *= 5;
|
||||
b *= 3;
|
||||
c *= 10;
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b0
|
||||
title: 複合賦值之 -=
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2Qv7AV'
|
||||
forumTopicId: 16660
|
||||
dashedName: compound-assignment-with-augmented-subtraction
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
與 `+=` 操作符類似,`-=` 操作符用來對一個變量進行減法賦值操作。
|
||||
|
||||
```js
|
||||
myVar = myVar - 5;
|
||||
```
|
||||
|
||||
將從 `myVar` 中減去 `5`。 等價於:
|
||||
|
||||
```js
|
||||
myVar -= 5;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `-=` 操作符對 `a`、`b` 和 `c` 實現相減賦值操作。
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` 應該等於 `5`。
|
||||
|
||||
```js
|
||||
assert(a === 5);
|
||||
```
|
||||
|
||||
`b` 應該等於 `-6`。
|
||||
|
||||
```js
|
||||
assert(b === -6);
|
||||
```
|
||||
|
||||
`c` 應該等於 `2`。
|
||||
|
||||
```js
|
||||
assert(c === 2);
|
||||
```
|
||||
|
||||
應該對每個變量使用 `-=` 操作符。
|
||||
|
||||
```js
|
||||
assert(code.match(/-=/g).length === 3);
|
||||
```
|
||||
|
||||
不要修改註釋上面的代碼。
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 11;
|
||||
var b = 9;
|
||||
var c = 3;
|
||||
|
||||
// Only change code below this line
|
||||
a = a - 6;
|
||||
b = b - 15;
|
||||
c = c - 1;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 11;
|
||||
var b = 9;
|
||||
var c = 3;
|
||||
|
||||
a -= 6;
|
||||
b -= 15;
|
||||
c -= 1;
|
||||
```
|
@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b7
|
||||
title: 用加號運算符連接字符串
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNpM8AN'
|
||||
forumTopicId: 16802
|
||||
dashedName: concatenating-strings-with-plus-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在 JavaScript 中,當 `+` 操作符被用於一個 `String` 類型的值的時候,它被稱作<dfn>拼接</dfn>操作符。 你可以通過<dfn>拼接</dfn>其他字符串來創建一個新的字符串。
|
||||
|
||||
**例如:**
|
||||
|
||||
```js
|
||||
'My name is Alan,' + ' I concatenate.'
|
||||
```
|
||||
|
||||
**提示:**注意空格。 拼接操作不會在兩個字符串之間添加空格。所以,如果想加上空格的話,你需要自己在字符串裏面添加。
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. " + "I come second.";
|
||||
```
|
||||
|
||||
字符串 `I come first. I come second.` 將顯示在控制檯中。
|
||||
# --instructions--
|
||||
|
||||
使用 `+` 操作符連接字符串`This is the start.` 和 `This is the end.` 賦值給 `myStr` 。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` 的值應該是 `This is the start. This is the end.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the start. This is the end.');
|
||||
```
|
||||
|
||||
應使用 `+` 操作符創建 `myStr`。
|
||||
|
||||
```js
|
||||
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
|
||||
```
|
||||
|
||||
應使用 `var` 關鍵字創建 `myStr`。
|
||||
|
||||
```js
|
||||
assert(/var\s+myStr/.test(code));
|
||||
```
|
||||
|
||||
應把結果賦值給 `myStr` 變量。
|
||||
|
||||
```js
|
||||
assert(/myStr\s*=/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if(typeof myStr === 'string') {
|
||||
return 'myStr = "' + myStr + '"';
|
||||
} else {
|
||||
return 'myStr is not a string';
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "This is the start. " + "This is the end.";
|
||||
```
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b8
|
||||
title: 用 += 運算符連接字符串
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmmC4'
|
||||
forumTopicId: 16803
|
||||
dashedName: concatenating-strings-with-the-plus-equals-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們還可以使用 `+=` 運算符來<dfn>拼接</dfn>字符串到現有字符串變量的結尾。 對於那些被分割成幾段的長的字符串來說,這一操作是非常有用的。
|
||||
|
||||
**提示:**注意空格。 拼接操作不會在兩個字符串之間添加空格,所以,如果想要加上空格的話,你需要自己在字符串裏面添加。
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. ";
|
||||
ourStr += "I come second.";
|
||||
```
|
||||
|
||||
`ourStr` 現在內容爲字符串 `I come first. I come second.`
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `+=` 操作符,多行合併字符串 `This is the first sentence.` 和 `This is the second sentence.` ,並賦值給 `myStr` 。 像編輯器裏顯示的那樣使用 `+=` 操作符。 先把第一個字符串賦值給 `myStr`,然後拼接第二個字符串。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` 的值應該是 `This is the first sentence. This is the second sentence.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the first sentence. This is the second sentence.');
|
||||
```
|
||||
|
||||
應該使用 `+=` 操作符創建 `myStr` 變量。
|
||||
|
||||
```js
|
||||
assert(code.match(/myStr\s*\+=\s*(["']).*\1/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if(typeof myStr === 'string') {
|
||||
return 'myStr = "' + myStr + '"';
|
||||
} else {
|
||||
return 'myStr is not a string';
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
|
||||
var myStr;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "This is the first sentence. ";
|
||||
myStr += "This is the second sentence.";
|
||||
```
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b9
|
||||
title: 用變量構造字符串
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqk8rf4'
|
||||
forumTopicId: 16805
|
||||
dashedName: constructing-strings-with-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
有時候你需要創建一個類似 [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)(填詞遊戲)風格的字符串。 通過使用連接運算符(`+`),你可以插入一個或多個變量來組成一個字符串。
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
var ourName = "freeCodeCamp";
|
||||
var ourStr = "Hello, our name is " + ourName + ", how are you?";
|
||||
```
|
||||
|
||||
`ourStr` 值爲 `Hello, our name is freeCodeCamp, how are you?`
|
||||
|
||||
# --instructions--
|
||||
|
||||
把你的名字賦值給變量 `myName`,然後把變量 `myName` 插入到字符串 `My name is` 和 `and I am well!` 之間,並把連接後的結果賦值給變量 `myStr`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myName` 應該是一個至少有 3 個字符的字符串。
|
||||
|
||||
```js
|
||||
assert(typeof myName !== 'undefined' && myName.length > 2);
|
||||
```
|
||||
|
||||
使用兩個 `+` 操作符創建包含 `myName` 的 `myStr` 變量。
|
||||
|
||||
```js
|
||||
assert(code.match(/["']\s*\+\s*myName\s*\+\s*["']/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
var output = [];
|
||||
if(typeof myName === 'string') {
|
||||
output.push('myName = "' + myName + '"');
|
||||
} else {
|
||||
output.push('myName is not a string');
|
||||
}
|
||||
if(typeof myStr === 'string') {
|
||||
output.push('myStr = "' + myStr + '"');
|
||||
} else {
|
||||
output.push('myStr is not a string');
|
||||
}
|
||||
return output.join('\n');
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
var myName;
|
||||
var myStr;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myName = "Bob";
|
||||
var myStr = "My name is " + myName + " and I am well!";
|
||||
```
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 56105e7b514f539506016a5e
|
||||
title: 使用 For 循環反向遍歷數組
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2R6BHa'
|
||||
forumTopicId: 16808
|
||||
dashedName: count-backwards-with-a-for-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
只要我們定義好合適的條件,for 循環也可以反向遍歷。
|
||||
|
||||
爲了讓每次遞減 2,我們需要改變 initialization、condition 和 final-expression。
|
||||
|
||||
設置 `i = 10`,並且當 `i > 0` 的時候才繼續循環。 我們使用 `i -= 2` 來讓 `i` 每次循環遞減 2。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 10; i > 0; i -= 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
循環結束後,`ourArray` 的值爲 `[10,8,6,4,2]`。 讓我們改變初始值和最後的表達式,這樣我們就可以按照奇數從後往前兩兩倒着數。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用一個 `for`循環,把從 9 到 1 的奇數添加到 `myArray`。
|
||||
|
||||
# --hints--
|
||||
|
||||
應該使用 `for` 循環。
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
應該使用數組方法 `push`。
|
||||
|
||||
```js
|
||||
assert(code.match(/myArray.push/));
|
||||
```
|
||||
|
||||
`myArray` 應該等於 `[9,7,5,3,1]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 9; i > 0; i -= 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
@ -0,0 +1,201 @@
|
||||
---
|
||||
id: 565bbe00e9cc8ac0725390f4
|
||||
title: 21 點遊戲
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KE7ty'
|
||||
forumTopicId: 16809
|
||||
dashedName: counting-cards
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在賭場 21 點遊戲中,玩家可以通過計算牌桌上已經發放的卡牌的高低值來讓自己在遊戲中保持優勢。 這就叫 [21 點算法](https://en.wikipedia.org/wiki/Card_counting)。
|
||||
|
||||
牌桌上的大值的卡牌更多,對玩家有利。 根據下面的表格,每張卡牌都被分配了一個值。 如果卡牌的值大於 0,那麼玩家應該追加賭注。 如果卡牌的值爲 0 或負數,玩家應該追加少許賭注甚至不追加賭注。
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>計數</th><th>卡牌</th></tr></thead><tbody><tr><td>+1</td><td>2, 3, 4, 5, 6</td></tr><tr><td>0</td><td>7, 8, 9</td></tr><tr><td>-1</td><td>10, 'J', 'Q', 'K', 'A'</td></tr></tbody></table>
|
||||
|
||||
請寫一個函數實現 21 點算法。 它根據參數 `card` 的值(見表格,可能是數字或者字符串)來遞增或遞減全局變量 `count`。 然後函數返回一個由當前 count(計數)和 `Bet`(當 count > 0 時)或 `Hold`(當 count <= 0 時) 拼接的字符串。 注意 count(計數)和玩家的決定(`Bet` 或 `Hold`)之間應該有空格。
|
||||
|
||||
**示例輸出:**`-3 Hold` 或者 `5 Bet`
|
||||
|
||||
**提示:**
|
||||
當卡牌爲 7、8、9 時,不要把 `count` 值重置爲 0。 不要返回一個數組。
|
||||
輸出結果中不要包含單引號或雙引號。
|
||||
|
||||
# --hints--
|
||||
|
||||
卡牌序列 2、3、4、5、6 應該返回 `5 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(2);
|
||||
cc(3);
|
||||
cc(4);
|
||||
cc(5);
|
||||
var out = cc(6);
|
||||
if (out === '5 Bet') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
卡牌序列 7、8、9 應該返回 `0 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(7);
|
||||
cc(8);
|
||||
var out = cc(9);
|
||||
if (out === '0 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
卡牌序列 10、J、Q、K、A 應該返回 `-5 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(10);
|
||||
cc('J');
|
||||
cc('Q');
|
||||
cc('K');
|
||||
var out = cc('A');
|
||||
if (out === '-5 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
卡牌序列 3、7、Q、8、A 應該返回 `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(3);
|
||||
cc(7);
|
||||
cc('Q');
|
||||
cc(8);
|
||||
var out = cc('A');
|
||||
if (out === '-1 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
卡牌序列 2、J、9、2、7 應該返回 `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(2);
|
||||
cc('J');
|
||||
cc(9);
|
||||
cc(2);
|
||||
var out = cc(7);
|
||||
if (out === '1 Bet') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
卡牌序列 2、2、10 應該返回 `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(2);
|
||||
cc(2);
|
||||
var out = cc(10);
|
||||
if (out === '1 Bet') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
卡牌序列 3、2、A、10、K 應該返回 `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(3);
|
||||
cc(2);
|
||||
cc('A');
|
||||
cc(10);
|
||||
var out = cc('K');
|
||||
if (out === '-1 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
|
||||
function cc(card) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
cc(2); cc(3); cc(7); cc('K'); cc('A');
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
function cc(card) {
|
||||
switch(card) {
|
||||
case 2:
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
case 6:
|
||||
count++;
|
||||
break;
|
||||
case 10:
|
||||
case 'J':
|
||||
case 'Q':
|
||||
case 'K':
|
||||
case 'A':
|
||||
count--;
|
||||
}
|
||||
if(count > 0) {
|
||||
return count + " Bet";
|
||||
} else {
|
||||
return count + " Hold";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,54 @@
|
||||
---
|
||||
id: cf1391c1c11feddfaeb4bdef
|
||||
title: 創建一個小數
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GEuW'
|
||||
forumTopicId: 16826
|
||||
dashedName: create-decimal-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們也可以把小數存儲到變量中。 小數有時候也被稱作<dfn>浮點數</dfn>或者 <dfn>floats</dfn>。
|
||||
|
||||
**提示:**不是所有的實數都可以用浮點數(<dfn>floating point</dfn>)來表示。 因爲可能產生四捨五入的錯誤, [查看詳情](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems)。
|
||||
|
||||
# --instructions--
|
||||
|
||||
創建一個變量 `myDecimal`,並給它賦值一個浮點數(例如 `5.7`)。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDecimal` 應該是一個數字。
|
||||
|
||||
```js
|
||||
assert(typeof myDecimal === 'number');
|
||||
```
|
||||
|
||||
`myDecimal` 應該包含小數點。
|
||||
|
||||
```js
|
||||
assert(myDecimal % 1 != 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){if(typeof myDecimal !== "undefined"){return myDecimal;}})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var ourDecimal = 5.7;
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDecimal = 9.9;
|
||||
```
|
@ -0,0 +1,61 @@
|
||||
---
|
||||
id: bd7123c9c443eddfaeb5bdef
|
||||
title: 聲明變量
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNanrHq'
|
||||
forumTopicId: 17556
|
||||
dashedName: declare-javascript-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在計算機科學中,<dfn>數據</dfn>就是一切,它對於計算機意義重大。 JavaScript 提供七種不同的<dfn>數據類型</dfn>,它們是 `undefined`(未定義)、`null`(空)、`boolean`(布爾型)、`string`(字符串)、`symbol`、`number`(數字)、`bigint`(可以表示任意大的整數)和 `object`(對象)。
|
||||
|
||||
例如,計算機區分數字,例如 `12`,和由字符組成的字符串 `strings`,例如 `"12"`、`"dog"` 或 `"123 cats"`。 計算機可以對數字執行數學運算,但不能對字符串執行數學運算。
|
||||
|
||||
<dfn>變量</dfn>允許計算機以一種動態的形式來存儲和操作數據, 即通過操作指向數據的指針而不是數據本身來實現。 以上八種數據類型中的任何一種都可以存儲到一個變量中。
|
||||
|
||||
變量非常類似於你在數學中使用的 x、y 變量,都是以一個簡單命名的名稱來代替我們賦值給它的數據。 計算機中的變量與數學中的變量不同的是,計算機可以在不同的時間存儲不同類型的變量。
|
||||
|
||||
通過在變量前面使用關鍵字 `var`,<dfn>聲明</dfn>一個變量,例如:
|
||||
|
||||
```js
|
||||
var ourName;
|
||||
```
|
||||
|
||||
上面代碼的意思是創建一個名爲 `ourName` 的變量。 在 JavaScript 中我們以分號結束語句。 變量名稱可以由數字、字母、美元符號 `$` 或者下劃線 `_` 組成,但是不能包含空格或者以數字爲開頭。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `var` 關鍵字來創建一個名爲 `myName` 的變量。
|
||||
|
||||
**提示:**
|
||||
如果遇到困難了,請看下 `ourName` 的例子是怎麼寫的。
|
||||
|
||||
# --hints--
|
||||
|
||||
使用 `var` 關鍵字定義一個變量 `myName`,並使用分號結尾。
|
||||
|
||||
```js
|
||||
assert(/var\s+myName\s*;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myName !== "undefined"){(function(v){return v;})(myName);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myName;
|
||||
```
|
@ -0,0 +1,81 @@
|
||||
---
|
||||
id: bd7123c9c444eddfaeb5bdef
|
||||
title: 聲明字符串變量
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvWU6'
|
||||
forumTopicId: 17557
|
||||
dashedName: declare-string-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
之前我們寫過這樣的代碼:
|
||||
|
||||
```js
|
||||
var myName = "your name";
|
||||
```
|
||||
|
||||
`"your name"` 被稱作<dfn>字符串</dfn><dfn>字面量</dfn>。 這是一個字符串,因爲它是一系列包含在單引號或雙引號中的零或多個字符。
|
||||
|
||||
# --instructions--
|
||||
|
||||
創建兩個新的字符串變量:`myFirstName` 和 `myLastName`,並用你的姓和名分別爲它們賦值。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myFirstName` 應該是一個字符串,至少包含一個字符。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myFirstName !== 'undefined' &&
|
||||
typeof myFirstName === 'string' &&
|
||||
myFirstName.length > 0
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
`myLastName` 應該是一個字符串,至少包含一個字符。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myLastName !== 'undefined' &&
|
||||
typeof myLastName === 'string' &&
|
||||
myLastName.length > 0
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myFirstName !== "undefined" && typeof myLastName !== "undefined"){(function(){return myFirstName + ', ' + myLastName;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myFirstName = "Alan";
|
||||
var myLastName = "Turing";
|
||||
```
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ad
|
||||
title: 數字遞減
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KeS2'
|
||||
forumTopicId: 17558
|
||||
dashedName: decrement-a-number-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
使用自減符號 `--`,你可以很方便地對一個變量執行<dfn>自減</dfn>或者 -1 運算。
|
||||
|
||||
```js
|
||||
i--;
|
||||
```
|
||||
|
||||
等效於:
|
||||
|
||||
```js
|
||||
i = i - 1;
|
||||
```
|
||||
|
||||
**注意:**`i--;` 這種寫法省去了書寫等號的必要。
|
||||
|
||||
# --instructions--
|
||||
|
||||
修改代碼,使用 `--` 符號對 `myVar` 執行自減操作。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar` 應該等於`10`。
|
||||
|
||||
```js
|
||||
assert(myVar === 10);
|
||||
```
|
||||
|
||||
應該修改 `myVar = myVar - 1;`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
應該對 `myVar` 使用 `--` 運算符。
|
||||
|
||||
```js
|
||||
assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code));
|
||||
```
|
||||
|
||||
不應修改註釋上方的代碼。
|
||||
|
||||
```js
|
||||
assert(/var myVar = 11;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'myVar = ' + z;})(myVar);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myVar = 11;
|
||||
|
||||
// Only change code below this line
|
||||
myVar = myVar - 1;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myVar = 11;
|
||||
myVar--;
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d3
|
||||
title: 刪除對象的屬性
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqKdTv'
|
||||
forumTopicId: 17560
|
||||
dashedName: delete-properties-from-a-javascript-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們同樣可以刪除對象的屬性,例如:
|
||||
|
||||
```js
|
||||
delete ourDog.bark;
|
||||
```
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"],
|
||||
"bark": "bow-wow"
|
||||
};
|
||||
|
||||
delete ourDog.bark;
|
||||
```
|
||||
|
||||
在上面代碼的最後一行中,`ourDog` 是這樣的:
|
||||
|
||||
```js
|
||||
{
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
刪除 `myDog` 對象的 `tails` 屬性。 可以使用點操作符或者中括號操作符。
|
||||
|
||||
# --hints--
|
||||
|
||||
應該從 `myDog` 中刪除 `tails` 屬性。
|
||||
|
||||
```js
|
||||
assert(typeof myDog === 'object' && myDog.tails === undefined);
|
||||
```
|
||||
|
||||
不要修改 `myDog` 的初始化代碼。
|
||||
|
||||
```js
|
||||
assert(code.match(/"tails": 1/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"],
|
||||
"bark": "woof"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"],
|
||||
"bark": "woof"
|
||||
};
|
||||
delete myDog.tails;
|
||||
```
|
@ -0,0 +1,56 @@
|
||||
---
|
||||
id: bd7993c9ca9feddfaeb7bdef
|
||||
title: 兩個小數相除
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZe9AW'
|
||||
forumTopicId: 18255
|
||||
dashedName: divide-one-decimal-by-another-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
現在讓我們將一個小數除以另一個小數。
|
||||
|
||||
# --instructions--
|
||||
|
||||
改變數值 `0.0` 的值讓變量 `quotient` 的值等於 `2.2`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`quotient` 的值應該等於`2.2`。
|
||||
|
||||
```js
|
||||
assert(quotient === 2.2);
|
||||
```
|
||||
|
||||
使用 `/` 運算符將 4.4 除以 2。
|
||||
|
||||
```js
|
||||
assert(/4\.40*\s*\/\s*2\.*0*/.test(code));
|
||||
```
|
||||
|
||||
quotient 變量應該只被賦值一次。
|
||||
|
||||
```js
|
||||
assert(code.match(/quotient/g).length === 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y){return 'quotient = '+y;})(quotient);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var quotient = 0.0 / 2.0; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var quotient = 4.4 / 2.0;
|
||||
```
|
@ -0,0 +1,59 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb6bdef
|
||||
title: 除法運算
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqkbdAr'
|
||||
forumTopicId: 17566
|
||||
dashedName: divide-one-number-by-another-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們可以在 JavaScript 中做除法運算。
|
||||
|
||||
JavaScript 中使用 `/` 符號做除法運算。
|
||||
|
||||
**示例**
|
||||
|
||||
```js
|
||||
myVar = 16 / 2;
|
||||
```
|
||||
|
||||
現在,變量 `myVar` 的值爲 `8`。
|
||||
# --instructions--
|
||||
|
||||
改變數值 `0` 來讓變量 `quotient` 的值等於 `2`。
|
||||
|
||||
# --hints--
|
||||
|
||||
要使 `quotient` 的值等於 2。
|
||||
|
||||
```js
|
||||
assert(quotient === 2);
|
||||
```
|
||||
|
||||
使用 `/` 運算符。
|
||||
|
||||
```js
|
||||
assert(/\d+\s*\/\s*\d+/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'quotient = '+z;})(quotient);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var quotient = 66 / 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var quotient = 66 / 33;
|
||||
```
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b6
|
||||
title: 轉義字符
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqRh6'
|
||||
forumTopicId: 17567
|
||||
dashedName: escape-sequences-in-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
引號不是字符串中唯一可以被轉義(<dfn>escaped</dfn>)的字符。 使用轉義字符有兩個原因:
|
||||
|
||||
1. 首先是可以讓你使用無法輸入的字符,例如退格。
|
||||
2. 其次是可以讓你在一個字符串中表示多個引號,而不會出錯。
|
||||
|
||||
我們在之前的挑戰中學到了這個。
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>代碼</th><th>輸出</th></tr></thead><tbody><tr><td><code>\'</code></td><td>單引號</td></tr><tr><td><code>\"</code></td><td>雙引號</td></tr><tr><td><code>\\</code></td><td>反斜槓</td></tr><tr><td><code>\n</code></td><td>換行符</td></tr><tr><td><code>\r</code></td><td>回車符</td></tr><tr><td><code>\t</code></td><td>製表符</td></tr><tr><td><code>\b</code></td><td>退格</td></tr><tr><td><code>\f</code></td><td>換頁符</td></tr></tbody></table>
|
||||
|
||||
*請注意,必須對反斜槓本身進行轉義,它才能顯示爲反斜槓。*
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用轉義序列把下面三行文本賦值給一個變量 `myStr`。
|
||||
|
||||
<blockquote>FirstLine<br> \SecondLine<br>ThirdLine</blockquote>
|
||||
|
||||
你需要使用轉義字符正確地插入特殊字符。 確保間距與上面文本一致,並且單詞或轉義字符之間沒有空格。
|
||||
|
||||
**注意:** `SecondLine` 是因爲鍵入了轉義字符(而不是空格),所以在那個位置。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` 不能包含空格。
|
||||
|
||||
```js
|
||||
assert(!/ /.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` 應包含字符串 `FirstLine`、`SecondLine` 和 `ThirdLine`(記得區分大小寫)。
|
||||
|
||||
```js
|
||||
assert(
|
||||
/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr)
|
||||
);
|
||||
```
|
||||
|
||||
`FirstLine` 後面應該是一個換行符 `\n`。
|
||||
|
||||
```js
|
||||
assert(/FirstLine\n/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` 應該包含一個製表符 `\t`,它在換行符後面。
|
||||
|
||||
```js
|
||||
assert(/\n\t/.test(myStr));
|
||||
```
|
||||
|
||||
`SecondLine` 前面應該是反斜槓 `\`。
|
||||
|
||||
```js
|
||||
assert(/\\SecondLine/.test(myStr));
|
||||
```
|
||||
|
||||
`SecondLine` 和 `ThirdLine` 之間應該是換行符。
|
||||
|
||||
```js
|
||||
assert(/SecondLine\nThirdLine/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` 應該只包含上面要求的字符。
|
||||
|
||||
```js
|
||||
assert(myStr === 'FirstLine\n\t\\SecondLine\nThirdLine');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if (myStr !== undefined){
|
||||
console.log('myStr:\n' + myStr);}})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
|
||||
```
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b5
|
||||
title: 轉義字符串中的引號
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvgSr'
|
||||
forumTopicId: 17568
|
||||
dashedName: escaping-literal-quotes-in-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
定義一個字符串必須要用單引號或雙引號來包裹它。 那麼當你的字符串裏面包含引號 `"` 或者 `'` 時該怎麼辦呢?
|
||||
|
||||
在 JavaScript 中,可以通過在引號前面使用<dfn>反斜槓</dfn>(`\`)來<dfn>轉義</dfn>引號。
|
||||
|
||||
```js
|
||||
var sampleStr = "Alan said, \"Peter is learning JavaScript\".";
|
||||
```
|
||||
|
||||
有了轉義符號,JavaScript 就知道這個單引號或雙引號並不是字符串的結尾,而是字符串內的字符。 所以,上面的字符串打印到控制檯的結果爲:
|
||||
|
||||
```js
|
||||
Alan said, "Peter is learning JavaScript".
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用<dfn>反斜槓</dfn>給 `myStr` 變量賦值一個字符串,這樣如果你要打印它到控制檯,將會看到:
|
||||
|
||||
```js
|
||||
I am a "double quoted" string inside "double quotes".
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
你的代碼中應該包含兩個雙引號(`"`)以及四個轉義的雙引號(`\"`)。
|
||||
|
||||
```js
|
||||
assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2);
|
||||
```
|
||||
|
||||
變量 myStr 應該包含字符串 `I am a "double quoted" string inside "double quotes".`
|
||||
|
||||
```js
|
||||
assert(/I am a "double quoted" string inside "double quotes(\."|"\.)$/.test(myStr));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if(typeof myStr === 'string') {
|
||||
console.log("myStr = \"" + myStr + "\"");
|
||||
} else {
|
||||
console.log("myStr is undefined");
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr = ""; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
|
||||
```
|
@ -0,0 +1,69 @@
|
||||
---
|
||||
id: bd7123c9c448eddfaeb5bdef
|
||||
title: 查找字符串的長度
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqEAd'
|
||||
forumTopicId: 18182
|
||||
dashedName: find-the-length-of-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
你可以通過在字符串變量或字符串後面寫上 `.length` 來獲得 `String` 的長度。
|
||||
|
||||
```js
|
||||
console.log("Alan Peter".length);
|
||||
```
|
||||
|
||||
字符串 `10` 將會出現在控制檯中。
|
||||
|
||||
例如,我們創建了一個變量 `var firstName = "Charles"`,我們就可以通過使用 `firstName.length` 來獲得 `Charles` 字符串的長度。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `.length` 屬性來獲得變量 `lastName` 的長度,並把它賦值給變量 `lastNameLength`。
|
||||
|
||||
# --hints--
|
||||
|
||||
不能改變 `// Setup` 部分聲明的變量。
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/var lastNameLength = 0;/) &&
|
||||
code.match(/var lastName = "Lovelace";/)
|
||||
);
|
||||
```
|
||||
|
||||
`lastNameLength` 應該等於 8。
|
||||
|
||||
```js
|
||||
assert(typeof lastNameLength !== 'undefined' && lastNameLength === 8);
|
||||
```
|
||||
|
||||
你應該使用 `.length` 獲取 `lastName` 的長度,像這樣 `lastName.length`。
|
||||
|
||||
```js
|
||||
assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
lastNameLength = lastName;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
lastNameLength = lastName.length;
|
||||
```
|
@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ae
|
||||
title: 求餘運算
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWP24Ub'
|
||||
forumTopicId: 18184
|
||||
dashedName: finding-a-remainder-in-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>remainder</dfn> 求餘運算符 `%` 返回兩個數相除得到的餘數
|
||||
|
||||
**示例**
|
||||
|
||||
<blockquote>5 % 2 = 1 因爲<br>Math.floor(5 / 2) = 2 (商)<br>2 * 2 = 4<br>5 - 4 = 1 (餘數)</blockquote>
|
||||
|
||||
**用法**
|
||||
在數學中,判斷一個數是奇數還是偶數,只需要判斷這個數除以 `2` 得到的餘數是 0 還是 1。
|
||||
|
||||
<blockquote>17 % 2 = 1(17 是奇數)<br>48 % 2 = 0(48 是偶數)</blockquote>
|
||||
|
||||
**提示**餘數運算符(<dfn>remainder</dfn>)有時被錯誤地稱爲“模數”運算符。 它與模數非常相似,但不能用於負數的運算。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 <dfn>remainder</dfn> (`%`)運算符,計算 `11` 除以 `3` 的餘數,並把餘數賦給變量 `remainder`。
|
||||
|
||||
# --hints--
|
||||
|
||||
變量 `remainder` 應該被初始化。
|
||||
|
||||
```js
|
||||
assert(/var\s+?remainder/.test(code));
|
||||
```
|
||||
|
||||
`remainder` 的值應該等於 `2`。
|
||||
|
||||
```js
|
||||
assert(remainder === 2);
|
||||
```
|
||||
|
||||
你應該使用 `%` 運算符。
|
||||
|
||||
```js
|
||||
assert(/\s+?remainder\s*?=\s*?.*%.*;?/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y){return 'remainder = '+y;})(remainder);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
|
||||
var remainder;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var remainder = 11 % 3;
|
||||
```
|
@ -0,0 +1,69 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb9bdef
|
||||
title: 使用 JavaScript 生成隨機分數
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cyWJJs3'
|
||||
forumTopicId: 18185
|
||||
dashedName: generate-random-fractions-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
隨機數非常適合用來創建隨機行爲。
|
||||
|
||||
在 JavaScript 中,可以用 `Math.random()` 生成一個在`0`(包括 0)到 `1`(不包括 1)之間的隨機小數, 因此 `Math.random()` 可能返回 `0`,但絕不會返回 `1`。
|
||||
|
||||
**提示:** [使用賦值運算符存儲值](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator)這一節講過,所有函數調用將在 `return` 執行之前結束,因此我們可以 `return`(返回)`Math.random()` 函數的值。
|
||||
|
||||
# --instructions--
|
||||
|
||||
更改 `randomFraction`,使其返回一個隨機數而不是 `0`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`randomFraction` 應該返回一個隨機數。
|
||||
|
||||
```js
|
||||
assert(typeof randomFraction() === 'number');
|
||||
```
|
||||
|
||||
`randomFraction` 應該返回一個小數。
|
||||
|
||||
```js
|
||||
assert((randomFraction() + '').match(/\./g));
|
||||
```
|
||||
|
||||
需要使用 `Math.random` 生成隨機的小數。
|
||||
|
||||
```js
|
||||
assert(code.match(/Math\.random/g).length >= 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){return randomFraction();})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function randomFraction() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
return 0;
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function randomFraction() {
|
||||
return Math.random();
|
||||
}
|
||||
```
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb1bdef
|
||||
title: 使用 JavaScript 生成隨機整數
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRn6bfr'
|
||||
forumTopicId: 18186
|
||||
dashedName: generate-random-whole-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
生成隨機小數很棒,但隨機數更有用的地方在於生成隨機整數。
|
||||
|
||||
<ol><li>用 <code>Math.random()</code> 生成一個隨機小數。</li><li>把這個隨機小數乘以 <code>20</code>。</li><li>用 <code>Math.floor()</code> 向下取整,獲得它最近的整數。</li></ol>
|
||||
|
||||
記住 `Math.random()` 永遠不會返回 `1`。同時因爲我們是在向下取整,所以最終我們獲得的結果不可能有 `20`。 這確保了我們獲得了一個在 `0` 到 `19` 之間的整數。
|
||||
|
||||
把操作連綴起來,代碼類似於下面:
|
||||
|
||||
```js
|
||||
Math.floor(Math.random() * 20);
|
||||
```
|
||||
|
||||
我們先調用 `Math.random()`,把它的結果乘以 20,然後把上一步的結果傳給 `Math.floor()`,最終通過向下取整獲得最近的整數。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用這個方法生成並返回 `0` 和 `9` 之間的隨機整數。
|
||||
|
||||
# --hints--
|
||||
|
||||
`randomWholeNum` 的結果應該是一個整數。
|
||||
|
||||
```js
|
||||
assert(
|
||||
typeof randomWholeNum() === 'number' &&
|
||||
(function () {
|
||||
var r = randomWholeNum();
|
||||
return Math.floor(r) === r;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
應該使用 `Math.random` 生成一個隨機數字。
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.random/g).length >= 1);
|
||||
```
|
||||
|
||||
應該將 `Math.random` 的結果乘以 10,以生成 0 到 9 之間的隨機數。
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) ||
|
||||
code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g)
|
||||
);
|
||||
```
|
||||
|
||||
應該使用 `Math.floor` 來刪除數字的十進制部分。
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.floor/g).length >= 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){return randomWholeNum();})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function randomWholeNum() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
return Math.random();
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function randomWholeNum() {
|
||||
return Math.floor(Math.random() * 10);
|
||||
}
|
||||
```
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb2bdef
|
||||
title: 生成某個範圍內的隨機整數
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm83yu6'
|
||||
forumTopicId: 18187
|
||||
dashedName: generate-random-whole-numbers-within-a-range
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
我們之前生成的隨機數是在 0 到某個數之間,現在我們要生成的隨機數是在兩個指定的數之間。
|
||||
|
||||
我們需要定義一個最小值 `min` 和一個最大值 `max`。
|
||||
|
||||
下面是我們將要使用的方法, 仔細看看並嘗試理解這行代碼到底在幹嘛:
|
||||
|
||||
```js
|
||||
Math.floor(Math.random() * (max - min + 1)) + min
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
創建一個函數 `randomRange`,參數爲 `myMin` 和 `myMax`,返回一個在 `myMin`(包括 myMin)和 `myMax`(包括 myMax)之間的隨機整數。
|
||||
|
||||
# --hints--
|
||||
|
||||
`randomRange` 返回的隨機數應該大於或等於 `myMin`。
|
||||
|
||||
```js
|
||||
assert(calcMin === 5);
|
||||
```
|
||||
|
||||
`randomRange` 返回的隨機數應該小於或等於 `myMax`。
|
||||
|
||||
```js
|
||||
assert(calcMax === 15);
|
||||
```
|
||||
|
||||
`randomRange` 應該返回一個隨機整數,而不是小數。
|
||||
|
||||
```js
|
||||
assert(randomRange(0, 1) % 1 === 0);
|
||||
```
|
||||
|
||||
`randomRange` 應該使用 `myMax` 和 `myMin`,並且返回兩者之間的隨機數。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
code.match(/myMax/g).length > 1 &&
|
||||
code.match(/myMin/g).length > 2 &&
|
||||
code.match(/Math.floor/g) &&
|
||||
code.match(/Math.random/g)
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
var calcMin = 100;
|
||||
var calcMax = -100;
|
||||
for(var i = 0; i < 100; i++) {
|
||||
var result = randomRange(5,15);
|
||||
calcMin = Math.min(calcMin, result);
|
||||
calcMax = Math.max(calcMax, result);
|
||||
}
|
||||
(function(){
|
||||
if(typeof myRandom === 'number') {
|
||||
return "myRandom = " + myRandom;
|
||||
} else {
|
||||
return "myRandom undefined";
|
||||
}
|
||||
})()
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function randomRange(myMin, myMax) {
|
||||
// Only change code below this line
|
||||
return 0;
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function randomRange(myMin, myMax) {
|
||||
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
|
||||
}
|
||||
```
|
@ -0,0 +1,128 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244be
|
||||
title: 全局作用域和函數
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQM7mCN'
|
||||
forumTopicId: 18193
|
||||
dashedName: global-scope-and-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在 JavaScript 中,<dfn>作用域</dfn>涉及到變量的作用範圍。 在函數外定義的變量具有 <dfn>全局</dfn> 作用域。 這意味着,具有全局作用域的變量可以在代碼的任何地方被調用。
|
||||
|
||||
這些沒有使用 `var` 關鍵字定義的變量,會被自動創建在 `global` 作用域中,形成全局變量。 當在代碼其他地方無意間定義了一個變量,剛好變量名與全局變量相同,這時會產生意想不到的後果。 因此你應該總是使用 `var` 關鍵字來聲明你的變量。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `var`,在函數外聲明一個全局變量 `myGlobal`, 並給它一個初始值 `10`。
|
||||
|
||||
在函數 `fun1` 的內部,***不***使用 `var` 關鍵字,聲明 `oopsGlobal`,並給它賦值爲 `5`。
|
||||
|
||||
# --hints--
|
||||
|
||||
應定義 `myGlobal`。
|
||||
|
||||
```js
|
||||
assert(typeof myGlobal != 'undefined');
|
||||
```
|
||||
|
||||
`myGlobal` 的值應爲 `10`。
|
||||
|
||||
```js
|
||||
assert(myGlobal === 10);
|
||||
```
|
||||
|
||||
應使用 `var` 關鍵字定義 `myGlobal`。
|
||||
|
||||
```js
|
||||
assert(/var\s+myGlobal/.test(code));
|
||||
```
|
||||
|
||||
`oopsGlobal` 應爲全局變量,值爲 `5`。
|
||||
|
||||
```js
|
||||
assert(typeof oopsGlobal != 'undefined' && oopsGlobal === 5);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
var logOutput = "";
|
||||
var originalConsole = console
|
||||
function capture() {
|
||||
var nativeLog = console.log;
|
||||
console.log = function (message) {
|
||||
logOutput = message;
|
||||
if(nativeLog.apply) {
|
||||
nativeLog.apply(originalConsole, arguments);
|
||||
} else {
|
||||
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
|
||||
nativeLog(nativeMsg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function uncapture() {
|
||||
console.log = originalConsole.log;
|
||||
}
|
||||
var oopsGlobal;
|
||||
capture();
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
fun1();
|
||||
fun2();
|
||||
uncapture();
|
||||
(function() { return logOutput || "console.log never called"; })();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Declare the myGlobal variable below this line
|
||||
|
||||
|
||||
function fun1() {
|
||||
// Assign 5 to oopsGlobal Here
|
||||
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
function fun2() {
|
||||
var output = "";
|
||||
if (typeof myGlobal != "undefined") {
|
||||
output += "myGlobal: " + myGlobal;
|
||||
}
|
||||
if (typeof oopsGlobal != "undefined") {
|
||||
output += " oopsGlobal: " + oopsGlobal;
|
||||
}
|
||||
console.log(output);
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myGlobal = 10;
|
||||
|
||||
function fun1() {
|
||||
oopsGlobal = 5;
|
||||
}
|
||||
|
||||
function fun2() {
|
||||
var output = "";
|
||||
if(typeof myGlobal != "undefined") {
|
||||
output += "myGlobal: " + myGlobal;
|
||||
}
|
||||
if(typeof oopsGlobal != "undefined") {
|
||||
output += " oopsGlobal: " + oopsGlobal;
|
||||
}
|
||||
console.log(output);
|
||||
}
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c0
|
||||
title: 函數中的全局作用域和局部作用域
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QwKH2'
|
||||
forumTopicId: 18194
|
||||
dashedName: global-vs--local-scope-in-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
一個程序中有可能具有相同名稱的<dfn>局部</dfn>變量 和<dfn>全局</dfn>變量。 在這種情況下,`local` 變量將會優先於`global`變量。
|
||||
|
||||
下面爲例:
|
||||
|
||||
```js
|
||||
var someVar = "Hat";
|
||||
function myFun() {
|
||||
var someVar = "Head";
|
||||
return someVar;
|
||||
}
|
||||
```
|
||||
|
||||
函數 `myFun` 將會返回 `Head`,因爲 `local` 變量優先級更高。
|
||||
|
||||
# --instructions--
|
||||
|
||||
給 `myOutfit` 添加一個局部變量來將 `outerWear` 的值重載爲 `sweater`。
|
||||
|
||||
# --hints--
|
||||
|
||||
不要修改全局變量 `outerWear` 的值。
|
||||
|
||||
```js
|
||||
assert(outerWear === 'T-Shirt');
|
||||
```
|
||||
|
||||
`myOutfit` 應該返回 `sweater`。
|
||||
|
||||
```js
|
||||
assert(myOutfit() === 'sweater');
|
||||
```
|
||||
|
||||
不要修改 return 語句。
|
||||
|
||||
```js
|
||||
assert(/return outerWear/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var outerWear = "T-Shirt";
|
||||
|
||||
function myOutfit() {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return outerWear;
|
||||
}
|
||||
|
||||
myOutfit();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var outerWear = "T-Shirt";
|
||||
function myOutfit() {
|
||||
var outerWear = "sweater";
|
||||
return outerWear;
|
||||
}
|
||||
```
|
@ -0,0 +1,135 @@
|
||||
---
|
||||
id: 5664820f61c48e80c9fa476c
|
||||
title: 高爾夫代碼
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9ykNUR'
|
||||
forumTopicId: 18195
|
||||
dashedName: golf-code
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在[高爾夫](https://en.wikipedia.org/wiki/Golf)遊戲中,每個洞都有自己的標準桿數 `par`,代表着把球打進洞所揮杆的平均次數 `strokes`。 根據你把球打進洞所揮杆的次數 `strokes` 高於或低於 `par` 多少,有一個不同的暱稱(代表打高爾夫球的水平)。
|
||||
|
||||
函數將會傳送兩個參數,`par` 和 `strokes`。 根據下表返回正確的字符串。下表列出不同揮杆次數(從高到低)對應的字符串。
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>揮杆次數</th><th>返回字符串</th></tr></thead><tbody><tr><td>1</td><td>"Hole-in-one!"</td></tr><tr><td><= par - 2</td><td>"Eagle"</td></tr><tr><td>par - 1</td><td>"Birdie"</td></tr><tr><td>par</td><td>"Par"</td></tr><tr><td>par + 1</td><td>"Bogey"</td></tr><tr><td>par + 2</td><td>"Double Bogey"</td></tr><tr><td>>= par + 3</td><td>"Go Home!"</td></tr></tbody></table>
|
||||
|
||||
`par` 和 `strokes` 必須是數字而且是正數。 題目已定義字符串的數組,便於你操作。
|
||||
|
||||
# --hints--
|
||||
|
||||
`golfScore(4, 1)` 應該返回字符串 `Hole-in-one!`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(4, 2)` 應該返回字符串 `Eagle`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(5, 2)` 應該返回字符串 `Eagle`
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(4, 3)` 應該返回字符串 `Birdie`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 3) === 'Birdie');
|
||||
```
|
||||
|
||||
`golfScore(4, 4)` 應該返回字符串 `Par`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 4) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(1, 1)` 應該返回字符串 `Hole-in-one!`
|
||||
|
||||
```js
|
||||
assert(golfScore(1, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(5, 5)` 應該返回字符串 `Par`
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 5) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(4, 5)` 應該返回字符串 `Bogey`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 5) === 'Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 6)` 應該返回字符串 `Double Bogey`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 6) === 'Double Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 7)` 應該返回字符串 `Go Home!`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 7) === 'Go Home!');
|
||||
```
|
||||
|
||||
`golfScore(5, 9)` 應該返回字符串 `Go Home!`
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 9) === 'Go Home!');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
|
||||
function golfScore(par, strokes) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
golfScore(5, 4);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function golfScore(par, strokes) {
|
||||
if (strokes === 1) {
|
||||
return "Hole-in-one!";
|
||||
}
|
||||
|
||||
if (strokes <= par - 2) {
|
||||
return "Eagle";
|
||||
}
|
||||
|
||||
if (strokes === par - 1) {
|
||||
return "Birdie";
|
||||
}
|
||||
|
||||
if (strokes === par) {
|
||||
return "Par";
|
||||
}
|
||||
|
||||
if (strokes === par + 1) {
|
||||
return "Bogey";
|
||||
}
|
||||
|
||||
if(strokes === par + 2) {
|
||||
return "Double Bogey";
|
||||
}
|
||||
|
||||
return "Go Home!";
|
||||
}
|
||||
```
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ac
|
||||
title: 數字遞增
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GLT9'
|
||||
forumTopicId: 18201
|
||||
dashedName: increment-a-number-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
使用 `++`,我們可以很容易地對變量進行<dfn>自增</dfn>或者 +1 運算。
|
||||
|
||||
```js
|
||||
i++;
|
||||
```
|
||||
|
||||
等效於:
|
||||
|
||||
```js
|
||||
i = i + 1;
|
||||
```
|
||||
|
||||
**注意:**`i++;` 這種寫法省去了書寫等號的必要。
|
||||
|
||||
# --instructions--
|
||||
|
||||
修改代碼,使用 `++` 來對變量 `myVar` 進行自增操作。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar` 應該等於 `88`。
|
||||
|
||||
```js
|
||||
assert(myVar === 88);
|
||||
```
|
||||
|
||||
不應該使用賦值運算符。
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
應該使用 `++` 運算符。
|
||||
|
||||
```js
|
||||
assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code));
|
||||
```
|
||||
|
||||
不應該修改註釋上面的代碼。
|
||||
|
||||
```js
|
||||
assert(/var myVar = 87;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'myVar = ' + z;})(myVar);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myVar = 87;
|
||||
|
||||
// Only change code below this line
|
||||
myVar = myVar + 1;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myVar = 87;
|
||||
myVar++;
|
||||
```
|
@ -0,0 +1,50 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244a9
|
||||
title: 使用賦值運算符初始化變量
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWJ4Bfb'
|
||||
forumTopicId: 301171
|
||||
dashedName: initializing-variables-with-the-assignment-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
通常在聲明變量的時候會給變量<dfn>初始化</dfn>一個初始值。
|
||||
|
||||
```js
|
||||
var myVar = 0;
|
||||
```
|
||||
|
||||
創建一個名爲 `myVar` 的變量,並指定其初始值爲 `0`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
通過關鍵字 `var` 定義一個變量 `a`,並且給它一個初始值 `9`。
|
||||
|
||||
# --hints--
|
||||
|
||||
應該初始化 `a` 的值爲 `9`。
|
||||
|
||||
```js
|
||||
assert(/var\s+a\s*=\s*9(\s*;?\s*)$/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof a !== 'undefined') {(function(a){return "a = " + a;})(a);} else { (function() {return 'a is undefined';})(); }
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 9;
|
||||
```
|
@ -0,0 +1,114 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244db
|
||||
title: 介紹 else if 語句
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJ2hm'
|
||||
forumTopicId: 18206
|
||||
dashedName: introducing-else-if-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
如果你有多個條件語句,你可以通過 `else if` 語句把 `if` 語句鏈起來。
|
||||
|
||||
```js
|
||||
if (num > 15) {
|
||||
return "Bigger than 15";
|
||||
} else if (num < 5) {
|
||||
return "Smaller than 5";
|
||||
} else {
|
||||
return "Between 5 and 15";
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `else if` 實現同樣的效果。
|
||||
|
||||
# --hints--
|
||||
|
||||
你應該至少有兩個 `else` 表達式。
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 1);
|
||||
```
|
||||
|
||||
你應該至少有兩個 `if` 表達式。
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 1);
|
||||
```
|
||||
|
||||
應該關閉每一個 `if else` 代碼塊。
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(
|
||||
/if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s+if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s*\{[\s\S]+\s*\}/
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
`testElseIf(0)` 應該返回字符串 `Smaller than 5`
|
||||
|
||||
```js
|
||||
assert(testElseIf(0) === 'Smaller than 5');
|
||||
```
|
||||
|
||||
`testElseIf(5)` 應該返回字符串 `Between 5 and 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(5) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(7)` 應該返回字符串 `Between 5 and 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(7) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(10)` 應該返回字符串 `Between 5 and 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(10) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(12)` 應該返回字符串 `Greater than 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(12) === 'Greater than 10');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testElseIf(val) {
|
||||
if (val > 10) {
|
||||
return "Greater than 10";
|
||||
}
|
||||
|
||||
if (val < 5) {
|
||||
return "Smaller than 5";
|
||||
}
|
||||
|
||||
return "Between 5 and 10";
|
||||
}
|
||||
|
||||
testElseIf(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testElseIf(val) {
|
||||
if(val > 10) {
|
||||
return "Greater than 10";
|
||||
} else if(val < 5) {
|
||||
return "Smaller than 5";
|
||||
} else {
|
||||
return "Between 5 and 10";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,106 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244da
|
||||
title: 介紹 else 語句
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cek4Efq'
|
||||
forumTopicId: 18207
|
||||
dashedName: introducing-else-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
當 `if` 語句的條件爲真,會執行大括號裏的代碼。 那如果條件爲假呢? 正常情況下什麼也不會發生。 使用 `else` 語句,可以執行當條件爲假時相應的代碼。
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
return "Bigger than 10";
|
||||
} else {
|
||||
return "10 or Less";
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
請把多個 `if` 語句合併爲一個 `if/else` 語句。
|
||||
|
||||
# --hints--
|
||||
|
||||
應該只有一個 `if` 語句。
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
應該使用一個 `else` 語句。
|
||||
|
||||
```js
|
||||
assert(/else/g.test(code));
|
||||
```
|
||||
|
||||
`testElse(4)` 應該返回字符串 `5 or Smaller`
|
||||
|
||||
```js
|
||||
assert(testElse(4) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(5)` 應該返回字符串 `5 or Smaller`
|
||||
|
||||
```js
|
||||
assert(testElse(5) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(6)` 應該返回字符串 `Bigger than 5`
|
||||
|
||||
```js
|
||||
assert(testElse(6) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
`testElse(10)` 應該返回字符串 `Bigger than 5`
|
||||
|
||||
```js
|
||||
assert(testElse(10) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
不要修改相應註釋的上面或下面的代碼。
|
||||
|
||||
```js
|
||||
assert(/var result = "";/.test(code) && /return result;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testElse(val) {
|
||||
var result = "";
|
||||
// Only change code below this line
|
||||
|
||||
if (val > 5) {
|
||||
result = "Bigger than 5";
|
||||
}
|
||||
|
||||
if (val <= 5) {
|
||||
result = "5 or Smaller";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return result;
|
||||
}
|
||||
|
||||
testElse(4);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testElse(val) {
|
||||
var result = "";
|
||||
if(val > 5) {
|
||||
result = "Bigger than 5";
|
||||
} else {
|
||||
result = "5 or Smaller";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
@ -0,0 +1,67 @@
|
||||
---
|
||||
id: 56104e9e514f539506016a5c
|
||||
title: 使用 For 循環遍歷數組的奇數
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm8n7T9'
|
||||
forumTopicId: 18212
|
||||
dashedName: iterate-odd-numbers-with-a-for-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
對於循環,一次不必遞增一個。 通過更改我們的 `final-expression`,我們可以用偶數來計數。
|
||||
|
||||
初始化 `i = 0`,當 `i < 10` 的時候繼續循環。 `i += 2` 讓 `i` 每次循環之後增加 2。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 10; i += 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
循環結束後,`ourArray` 的值爲 `[0,2,4,6,8]`。 改變計數器(`initialization`) ,這樣我們可以用奇數來遞增。
|
||||
|
||||
# --instructions--
|
||||
|
||||
寫一個 `for` 循環,把從 1 到 9 的奇數添加到 `myArray`。
|
||||
|
||||
# --hints--
|
||||
|
||||
應該使用 `for` 循環。
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` 應該等於 `[1,3,5,7,9]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 10; i += 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 5675e877dbd60be8ad28edc6
|
||||
title: 使用 For 循環遍歷數組
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeR3HB'
|
||||
forumTopicId: 18216
|
||||
dashedName: iterate-through-an-array-with-a-for-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
JavaScript 中的一個常見任務是遍歷數組的內容。 一種方法是使用 `for` 循環。 下面的代碼將輸出數組 `arr` 的每個元素到控制檯:
|
||||
|
||||
```js
|
||||
var arr = [10, 9, 8, 7, 6];
|
||||
for (var i = 0; i < arr.length; i++) {
|
||||
console.log(arr[i]);
|
||||
}
|
||||
```
|
||||
|
||||
記住數組的索引從零開始的,這意味着數組的最後一個元素的下標是:`length - 1`(數組的長度 -1)。 我們這個循環的條件是 `i < arr.length`,當 `i` 的值爲 `length` 的時候循環就停止了。 在這個例子中,最後一個循環是 `i === 4`,也就是說,當 `i` 的值等於 `arr.length` 時,結果輸出 `6`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
聲明並初始化一個變量 `total` 值爲 `0`。 使用 `for` 循環,使得 `total` 的值爲 `myArr` 的數組中的每個元素的值的總和。
|
||||
|
||||
# --hints--
|
||||
|
||||
`total` 應該被聲明, 並且初始化值爲 0。
|
||||
|
||||
```js
|
||||
assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
|
||||
```
|
||||
|
||||
`total` 應該等於 20。
|
||||
|
||||
```js
|
||||
assert(total === 20);
|
||||
```
|
||||
|
||||
你應該使用 `for` 循環在 `myArr` 中遍歷。
|
||||
|
||||
```js
|
||||
assert(/for\s*\(/g.test(code) && /myArr\s*\[/g.test(code));
|
||||
```
|
||||
|
||||
不能直接把 `total` 設置成 20。
|
||||
|
||||
```js
|
||||
assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){if(typeof total !== 'undefined') { return "total = " + total; } else { return "total is undefined";}})()
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArr = [ 2, 3, 4, 5, 6];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArr = [ 2, 3, 4, 5, 6];
|
||||
var total = 0;
|
||||
|
||||
for (var i = 0; i < myArr.length; i++) {
|
||||
total += myArr[i];
|
||||
}
|
||||
```
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
id: 5a2efd662fb457916e1fe604
|
||||
title: do...while 循環
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqWGcp'
|
||||
forumTopicId: 301172
|
||||
dashedName: iterate-with-javascript-do---while-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
下一種循環叫作 `do...while` 循環。 它被稱爲 `do...while` 循環,是因爲不論什麼情況,它都會首先 `do`(運行)循環裏的第一部分代碼,然後 `while`(當)規定的條件被評估爲 `true`(真)的時候,它會繼續運行循環。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 0;
|
||||
do {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
上面的示例行爲類似於其他類型的循環,由此產生的數組將看起來像 `[0, 1, 2, 3, 4]`。 然而,`do...while` 不同於其他循環的地方,是第一次循環檢查失敗時的行爲。 讓我們看看代碼中的區別:這裏是一個常規的 `while` 循環,只要 `i < 5`,就會在循環中運行代碼:
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 5;
|
||||
while (i < 5) {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
這個例子中,定義了一個空數組 `ourArray` 以及一個值爲 5 的 `i` 。 當執行 `while` 循環時,因爲 `i` 不小於 5,所以循環條件爲 `false`,循環內的代碼將不會執行。 `ourArray` 最終沒有添加任何內容,因此示例中的所有代碼執行完時,ourArray 仍然是`[]`。 現在,看一下 `do...while` 循環。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 5;
|
||||
do {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
在這裏,和使用 `while` 循環一樣,將 `i` 的值初始化爲 5。 執行下一行時,沒有執行循環檢查,直接執行花括號內的代碼。 數組會添加一個元素,並在進行條件檢查之前遞增 `i`。 然後,在條件檢查時因爲 `i` 等於 6 不符合條件 `i < 5`,所以退出循環。 最終 `ourArray` 的值是 `[5]`。 本質上,`do...while` 循環確保循環內的代碼至少運行一次。 讓我們通過 `do...while` 循環將值添加到數組中。
|
||||
|
||||
# --instructions--
|
||||
|
||||
將代碼中的 `while` 循環更改爲 `do...while` 循環,將數字 `10` 添加到 `myArray` 中,代碼執行完時,`i` 等於 `11`。
|
||||
|
||||
# --hints--
|
||||
|
||||
你應該使用 `do...while` 循環。
|
||||
|
||||
```js
|
||||
assert(code.match(/do/g));
|
||||
```
|
||||
|
||||
`myArray` 應該等於 `[10]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [10]);
|
||||
```
|
||||
|
||||
`i` 應該等於 `11`。
|
||||
|
||||
```js
|
||||
assert.equal(i, 11);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
var i = 10;
|
||||
|
||||
// Only change code below this line
|
||||
while (i < 5) {
|
||||
myArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 10;
|
||||
do {
|
||||
myArray.push(i);
|
||||
i++;
|
||||
} while (i < 5)
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb5bdef
|
||||
title: for 循環
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yNVCe'
|
||||
forumTopicId: 18219
|
||||
dashedName: iterate-with-javascript-for-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
你可以使用循環多次執行相同的代碼。
|
||||
|
||||
JavaScript 中最常見的循環就是 `for`,它可以循環指定次數。
|
||||
|
||||
for 循環中的可選三個表達式用分號隔開:
|
||||
|
||||
`for (a; b; c)`,其中 `a` 爲初始化語句,`b` 是循環條件語句,`c` 是終止循環條件表達式。
|
||||
|
||||
初始化語句只會在執行循環開始之前執行一次。 它通常用於定義和設置你的循環變量。
|
||||
|
||||
循環條件語句會在每一輪循環的開始前執行,只要條件判斷爲 `true` 就會繼續執行循環。 當條件爲 `false` 的時候,循環將停止執行。 這意味着,如果條件在一開始就爲 false,這個循環將不會執行。
|
||||
|
||||
終止循環表達式在每次循環迭代結束, 在下一個條件檢查之前時執行,通常用來遞增或遞減循環計數。
|
||||
|
||||
在下面的例子中,先初始化 `i = 0`,條件 `i < 5` 爲 true 時,進入循環。 每次循環後 `i` 的值增加 `1`,然後執行終止循環條件表達式 `i++`。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 5; i++) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
最終 `ourArray` 的值爲 `[0,1,2,3,4]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `for` 循環把從 1 到 5 添加進 `myArray` 中。
|
||||
|
||||
# --hints--
|
||||
|
||||
你應該使用 `for` 循環。
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` 應該等於 `[1,2,3,4,5]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if (typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 6; i++) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb1bdef
|
||||
title: while 循環
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c8QbnCM'
|
||||
forumTopicId: 18220
|
||||
dashedName: iterate-with-javascript-while-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
你可以使用循環多次執行相同的代碼。
|
||||
|
||||
我們將學習的第一種類型的循環稱爲 `while` 循環,當 while 指定的條件爲真,循環纔會執行,反之不執行。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 0;
|
||||
while(i < 5) {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
在上面的代碼裏,`while` 循環執行 5 次把 0 到 4 的數字添加到 `ourArray` 數組裏。
|
||||
|
||||
讓我們通過 while 循環將值添加到數組中。
|
||||
|
||||
# --instructions--
|
||||
|
||||
通過一個 `while` 循環,把從 5 到 0(包括 5 和 0) 的值添加到 `myArray` 中。
|
||||
|
||||
# --hints--
|
||||
|
||||
你應該使用 `while` 循環。
|
||||
|
||||
```js
|
||||
assert(code.match(/while/g));
|
||||
```
|
||||
|
||||
`myArray` 應該等於 `[5,4,3,2,1,0]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 5;
|
||||
while(i >= 0) {
|
||||
myArray.push(i);
|
||||
i--;
|
||||
}
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bf
|
||||
title: 局部作用域和函數
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cd62NhM'
|
||||
forumTopicId: 18227
|
||||
dashedName: local-scope-and-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
在一個函數內聲明的變量,以及該函數的參數都具有局部(<dfn>local</dfn>)作用域。 這意味着它們只在該函數內可見。
|
||||
|
||||
這是在函數 `myTest` 內聲明局部變量 `loc` 的例子:
|
||||
|
||||
```js
|
||||
function myTest() {
|
||||
var loc = "foo";
|
||||
console.log(loc);
|
||||
}
|
||||
myTest();
|
||||
console.log(loc);
|
||||
```
|
||||
|
||||
`myTest()` 函數調用將在控制檯中顯示字符串 `foo`。 `console.log(loc)` 行會產生一個錯誤,因爲 `loc` 沒有定義在函數之外。
|
||||
|
||||
# --instructions--
|
||||
|
||||
編輯器有兩個 `console.log` 來幫助您瞭解正在發生的事情。 檢查控制檯的代碼輸出以查看它是如何改變的。 在 `myLocalScope` 中聲明一個本地變量 `myVar` 並運行測試。
|
||||
|
||||
**注意:** 控制檯仍將顯示 `ReferenceError: myVar is not defined`,但這不會導致測試失敗。
|
||||
|
||||
# --hints--
|
||||
|
||||
不應該包含全局的 `myVar` 變量。
|
||||
|
||||
```js
|
||||
function declared() {
|
||||
myVar;
|
||||
}
|
||||
assert.throws(declared, ReferenceError);
|
||||
```
|
||||
|
||||
需要定義局部的 `myVar` 變量。
|
||||
|
||||
```js
|
||||
assert(
|
||||
/functionmyLocalScope\(\)\{.*(var|let|const)myVar[\s\S]*}/.test(
|
||||
__helpers.removeWhiteSpace(code)
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function myLocalScope() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
console.log('inside myLocalScope', myVar);
|
||||
}
|
||||
myLocalScope();
|
||||
|
||||
// Run and check the console
|
||||
// myVar is not defined outside of myLocalScope
|
||||
console.log('outside myLocalScope', myVar);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function myLocalScope() {
|
||||
|
||||
// Only change code below this line
|
||||
var myVar;
|
||||
console.log('inside myLocalScope', myVar);
|
||||
}
|
||||
myLocalScope();
|
||||
|
||||
// Run and check the console
|
||||
// myVar is not defined outside of myLocalScope
|
||||
console.log('outside myLocalScope', myVar);
|
||||
```
|
@ -0,0 +1,109 @@
|
||||
---
|
||||
id: 5690307fddb111c6084545d7
|
||||
title: if else 語句中的邏輯順序
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cwNvMUV'
|
||||
forumTopicId: 18228
|
||||
dashedName: logical-order-in-if-else-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`if`、`else if` 語句中的代碼順序是很重要的。
|
||||
|
||||
在條件判斷語句中,代碼的執行順序是從上到下,所以你需要考慮清楚先執行哪一句,後執行哪一句。
|
||||
|
||||
這有兩個例子。
|
||||
|
||||
第一個例子:
|
||||
|
||||
```js
|
||||
function foo(x) {
|
||||
if (x < 1) {
|
||||
return "Less than one";
|
||||
} else if (x < 2) {
|
||||
return "Less than two";
|
||||
} else {
|
||||
return "Greater than or equal to two";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
第二個例子更改了代碼的執行順序:
|
||||
|
||||
```js
|
||||
function bar(x) {
|
||||
if (x < 2) {
|
||||
return "Less than two";
|
||||
} else if (x < 1) {
|
||||
return "Less than one";
|
||||
} else {
|
||||
return "Greater than or equal to two";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
這兩個函數看起來幾乎一模一樣,我們傳一個值進去看看它們有什麼區別。
|
||||
|
||||
```js
|
||||
foo(0)
|
||||
bar(0)
|
||||
```
|
||||
|
||||
`foo(0)` 將返回字符串 `Less than one`,`bar(0)` 將返回字符串 `Less than two`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
更改函數的邏輯順序以便通過所有的測試用例。
|
||||
|
||||
# --hints--
|
||||
|
||||
`orderMyLogic(4)` 應該返回字符串 `Less than 5`
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(4) === 'Less than 5');
|
||||
```
|
||||
|
||||
`orderMyLogic(6)` 應該返回字符串 `Less than 10`
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(6) === 'Less than 10');
|
||||
```
|
||||
|
||||
`orderMyLogic(11)`應該返回 `Greater than or equal to 10`。
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(11) === 'Greater than or equal to 10');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
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";
|
||||
}
|
||||
}
|
||||
|
||||
orderMyLogic(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
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";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cc
|
||||
title: 使用 pop() 操作數組
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRbVZAB'
|
||||
forumTopicId: 18236
|
||||
dashedName: manipulate-arrays-with-pop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
改變數組中數據的另一種方法是用 `.pop()` 函數。
|
||||
|
||||
`.pop()` 函數用來彈出一個數組末尾的值。 我們可以把這個彈出的值賦給一個變量存儲起來。 換句話說就是 `.pop()` 函數移除數組末尾的元素並返回這個元素。
|
||||
|
||||
數組中任何類型的元素(數值,字符串,甚至是數組)都可以被彈出來 。
|
||||
|
||||
```js
|
||||
var threeArr = [1, 4, 6];
|
||||
var oneDown = threeArr.pop();
|
||||
console.log(oneDown);
|
||||
console.log(threeArr);
|
||||
```
|
||||
|
||||
第一個 `console.log` 將顯示值 `6`,第二個將顯示值 `[1, 4]`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `.pop()` 函數移除 `myArray` 中的最後一個元素,並且把彈出的值賦給 `removedFromMyArray`。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` 應該只包含 `[["John", 23]]`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (d[0][0] == 'John' && d[0][1] === 23 && d[1] == undefined) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myArray)
|
||||
);
|
||||
```
|
||||
|
||||
對 `myArray` 使用 `pop()` 函數。
|
||||
|
||||
```js
|
||||
assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code));
|
||||
```
|
||||
|
||||
`removedFromMyArray` 應該只包含 `["cat", 2]`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (d[0] == 'cat' && d[1] === 2 && d[2] == undefined) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(removedFromMyArray)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
var removedFromMyArray = myArray.pop();
|
||||
```
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user