chore(i18n,learn): processed translations (#44851)

This commit is contained in:
camperbot
2022-01-21 01:00:18 +05:30
committed by GitHub
parent f866718a3d
commit 5c868af2b8
1696 changed files with 159426 additions and 69 deletions

View File

@ -0,0 +1,97 @@
---
id: a77dbc43c33f39daa4429b4f
title: ブール型の確認
challengeType: 5
forumTopicId: 16000
dashedName: boo-who
---
# --description--
値がブールプリミティブとして分類されるかどうかを確認してください。 `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);
```

View File

@ -0,0 +1,110 @@
---
id: a9bd25c716030ec90084d8a1
title: 配列をグループに分割する
challengeType: 5
forumTopicId: 16005
dashedName: chunky-monkey
---
# --description--
配列 (最初の引数) を `size` (2 番目の引数) の長さのグループに分割して 2 次元配列として返す関数を記述してください。
# --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);
```

View File

@ -0,0 +1,113 @@
---
id: acda2fb1324d9b0fa741e6b5
title: 末尾の一致判定
challengeType: 5
forumTopicId: 16006
dashedName: confirm-the-ending
---
# --description--
文字列 (最初の引数、`str`) が与えられたターゲット文字列 (2 番目の引数、`target`) で終わるかどうかを確認してください。
このチャレンジは ES2015 で導入された `.endsWith()` メソッドを使用すれば*解決できます*。 しかし、ここでは代わりに JavaScript の substring メソッドを使用してください。
# --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");
```

View File

@ -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);
```

View File

@ -0,0 +1,73 @@
---
id: a302f7aae1aa3152a5b413bc
title: 階乗計算
challengeType: 5
forumTopicId: 16013
dashedName: factorialize-a-number
---
# --description--
指定された整数の階乗を返してください。
指定された整数が `n` の場合、階乗は `n` 以下のすべての正の整数の積となります。
階乗はよく `n!` と簡略表記されます。
例: `5! = 1 * 2 * 3 * 4 * 5 = 120`
関数には 0 以上の整数だけが与えられます。
# --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);
```

View File

@ -0,0 +1,63 @@
---
id: adf08ec01beb4f99fc7a68f2
title: 偽値用心棒
challengeType: 5
forumTopicId: 16014
dashedName: falsy-bouncer
---
# --description--
すべての偽値を配列から取り除いてください。
JavaScriptにおける偽値とは、`false``null``0``""``undefined`、そして `NaN` です。
ヒント: それぞれの値をブール値に変換してみてください。
# --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]);
```

View File

@ -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");
```

View File

@ -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);
```

View File

@ -0,0 +1,117 @@
---
id: af2170cad53daa0770fabdea
title: ミューテーション
challengeType: 5
forumTopicId: 16025
dashedName: mutations
---
# --description--
配列の最初の要素内の文字列に、2 番目の要素内の文字列にあるすべての文字が含まれている場合に、`true` を返してください。
たとえば、`["hello", "Hello"]` は、2 番目の文字列内のすべての文字が最初の文字列に含まれているので、`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"]);
```

View File

@ -0,0 +1,84 @@
---
id: afcc8d540bea9ea2669306b6
title: 同じ文字列の繰り返し
challengeType: 5
forumTopicId: 16041
dashedName: repeat-a-string-repeat-a-string
---
# --description--
与えられた文字列 `str` (最初の引数) を `num` (2 番目の引数) 回繰り返してください。 `num` が正の数でない場合は、空の文字列を返してください。 このチャレンジでは、組み込みメソッドの `.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);
```

View File

@ -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]]);
```

View File

@ -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");
```

View File

@ -0,0 +1,98 @@
---
id: 579e2a2c335b9d72dd32e05c
title: Slice と Splice
challengeType: 5
forumTopicId: 301148
dashedName: slice-and-splice
---
# --description--
2 つの配列とインデックスが与えられています。
最初の配列の各要素を 2 番目の配列に順番にコピーしてください。
2 番目の配列のインデックス `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']
);
```
最初の配列のすべての要素を、元の順序で 2 番目の配列に追加する必要があります。 `frankenSplice([1, 2, 3, 4], [], 0)``[1, 2, 3, 4]` を返す必要があります。
```js
assert.deepEqual(frankenSplice([1, 2, 3, 4], [], 0), [1, 2, 3, 4]);
```
最初の配列は、関数の実行後も元のままにしておく必要があります。
```js
frankenSplice(testArr1, testArr2, 1);
assert.deepEqual(testArr1, [1, 2]);
```
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);
```

View File

@ -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");
```

View File

@ -0,0 +1,91 @@
---
id: ac6993d51946422351508a41
title: 文字列の省略
challengeType: 5
forumTopicId: 16089
dashedName: truncate-a-string
---
# --description--
文字列 (最初の引数) が指定された最大文字列長 (2 番目の引数) より長い場合、文字列を切り捨ててください。 末尾に `...` を付けて、省略された文字列を返してください。
# --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);
```

View File

@ -0,0 +1,143 @@
---
id: a24c1a4622e3c05097f71d67
title: 挿入位置
challengeType: 5
forumTopicId: 16094
dashedName: where-do-i-belong
---
# --description--
ソート後、配列 (最初の引数) の中で値 (2 番目の引数) を挿入すべきインデックスの最小値を返してください。 返される値は数値である必要があります。
たとえば、`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);
```

View File

@ -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>インデックス</dfn>を持ちます。 このインデックスは、配列内のアイテムの位置と参照方法を兼ねています。 ただし、JavaScript の配列では<dfn>インデックスは 0 から始まる</dfn>ことを覚えておいてください。つまり、配列の最初の要素の位置は ***0*** であって、1 ではないということです。 配列から要素を取得するには、インデックスをブラケット (角括弧) で囲み、配列の末尾に追加するか、または通常は配列オブジェクトを参照する変数に追加します。 これを<dfn>ブラケット記法</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` の 2 番目の位置 (インデックス `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";
```

View File

@ -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];
}
```

View File

@ -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>ミュータブル (変更可能)</dfn> です。 このチャレンジでは、配列をプログラム的に変更できる 2 つのメソッド `Array.push()``Array.unshift()` について見ていきます。
どちらのメソッドもパラメーターとして 1 つ以上の要素を受け取り、メソッド呼び出しの対象の配列にそれらの要素を追加します。`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` を末尾に追加して、数字 19 が順番に表示される配列を返すようにします。
# --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;
}
```

View File

@ -0,0 +1,93 @@
---
id: 587d78b3367417b2b2512b11
title: Splice() によるアイテムの追加
challengeType: 1
forumTopicId: 301152
dashedName: add-items-using-splice
---
# --description--
前回のチャレンジで説明しましたが、`splice()` は最大 3 つのパラメーターを取ることができます。 3 つ目のパラメーターは 1 つ以上の要素で構成されますが、このパラメーターを使用して配列に追加することができます。 これは、1 つまたは複数の要素を別の要素にすばやく入れ替えるのに非常に便利です。
```js
const numbers = [10, 11, 12, 12, 15];
const startIndex = 3;
const amountToDelete = 1;
numbers.splice(startIndex, amountToDelete, 13, 14);
console.log(numbers);
```
2 つ目の重複する `12` は削除され、同じインデックスに `13``14` が追加されます。 これで `numbers` 配列は `[ 10, 11, 12, 13, 14, 15 ]` となります。
ここでは、最初に数字の配列があります。 次に、`splice()` に、要素の削除を開始するインデックス (3) と、削除する要素の数 (1)、そして、同じインデックスに順に挿入される残りの引数 (13, 14) を渡します。 `amountToDelete` の後に、任意の数の要素 (コンマで区切る) を指定でき、それぞれを挿入できることに注意してください。
# --instructions--
関数 `htmlColorNames`を定義しました。これは、引数として HTML カラーの配列を取ります。 `splice()` を使用して関数を変更してください。配列の最初の 2 つの要素を削除し、それぞれの場所に `'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;
}
```

View File

@ -0,0 +1,124 @@
---
id: 587d7b7c367417b2b2512b18
title: JavaScript オブジェクトにキーと値のペアを追加する
challengeType: 1
forumTopicId: 301153
dashedName: add-key-value-pairs-to-javascript-objects
---
# --description--
最も基本的なオブジェクトは、<dfn>キーと値</dfn>のペアのみの集合です。 言い換えれば、これは<dfn>プロパティ</dfn> ( <dfn>キー</dfn>) と呼ばれる一意の識別子にマッピングされるデータ (<dfn></dfn>) の集まりです。 例を見てみましょう。
```js
const tekkenCharacter = {
player: 'Hwoarang',
fightingStyle: 'Tae Kwon Doe',
human: true
};
```
上記のコードは、`tekkenCharacter` という鉄拳ビデオゲームキャラクターのオブジェクトを定義しています。 オブジェクトには 3 つのプロパティがあり、それぞれが特定の値にマッピングされています。 "origin" などの新しいプロパティを追加したい場合は、`origin` をオブジェクトに割り当てます。
```js
tekkenCharacter.origin = 'South Korea';
```
これにはドット記法を使用しています。 `tekkenCharacter` オブジェクトを確認すると、`origin` プロパティが追加されたことがわかります。 Hwoarang は特徴的なオレンジ色の髪をしていました。 このプロパティをブラケット記法で追加することができます。
```js
tekkenCharacter['hair color'] = 'dyed orange';
```
プロパティにスペースがある場合や、プロパティに名前を付けるために変数を使用する場合には、ブラケット記法が必要となります。 上記の場合、プロパティを引用符で囲んで文字列として示すことで、表示されているとおりに追加されます。 引用符がなければ、変数として評価され、プロパティの名前は変数の値となります。 次に変数を含む例を示します。
```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--
3 つのエントリを持つ `foods` オブジェクトが作成されています。 任意の構文を用いて、このオブジェクトに新たに 3 つのエントリを追加してください。`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;
```

View File

@ -0,0 +1,93 @@
---
id: 587d7b7b367417b2b2512b14
title: indexOf() で要素の存在をチェックする
challengeType: 1
forumTopicId: 301154
dashedName: check-for-the-presence-of-an-element-with-indexof
---
# --description--
配列はいつでも変更、つまり*ミューテート*が可能であるため、 特定のデータが配列内のどこにあるのかや、その要素がまだ存在するかどうかについては何も保証されません。 幸い、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;
}
```

View File

@ -0,0 +1,161 @@
---
id: 587d7b7d367417b2b2512b1c
title: オブジェクトにプロパティがあるかどうかを確認する
challengeType: 1
forumTopicId: 301155
dashedName: check-if-an-object-has-a-property
---
# --description--
オブジェクトのキーの追加、変更、削除について学びました。 しかし、オブジェクトに特定のプロパティがあるかどうかを知りたいだけの場合はどうすればよいでしょうか? JavaScript には、そのことを調べるための 2 つの異なる方法があります。 1 つは `hasOwnProperty()` メソッドを使用する方法で、もう 1 つは `in` キーワードを使用する方法です。 `Alan` というプロパティを持つオブジェクト `users` がある場合、次のいずれかの方法でその存在を確認することができます。
```js
users.hasOwnProperty('Alan');
'Alan' in users;
```
どちらも `true` を返します。
# --instructions--
渡されたオブジェクトに `Alan``Jeff``Sarah``Ryan` の 4 つの名前すべてが含まれている場合は true を返し、そうでない場合は false を返すように、関数の記述を完成させてください。
# --hints--
`users` オブジェクトに直接アクセスすることはできません。
```js
assert(code.match(/users/gm).length <= 2)
```
`users` オブジェクトには `Alan`、`Jeff`、`Sarah`、`Ryan` のキーのみを含めます。
```js
assert(
'Alan' in users &&
'Jeff' in users &&
'Sarah' in users &&
'Ryan' in users &&
Object.keys(users).length === 4
);
```
関数 `isEveryoneHere` は、`Alan`、`Jeff`、`Sarah`、`Ryan` が渡されたオブジェクトのプロパティである場合、`true` を返す必要があります。
```js
assert(isEveryoneHere(users) === true);
```
関数 `isEveryoneHere` は、`Alan` が渡されたオブジェクトのプロパティではない場合、`false` を返す必要があります。
```js
assert(
(function () {
delete users.Alan;
return isEveryoneHere(users);
})() === false
);
```
関数 `isEveryoneHere` は、`Jeff` が渡されたオブジェクトのプロパティではない場合、`false` を返す必要があります。
```js
assert(
(function () {
delete users.Jeff;
return isEveryoneHere(users);
})() === false
);
```
関数 `isEveryoneHere` は、`Sarah` が渡されたオブジェクトのプロパティではない場合、`false` を返す必要があります。
```js
assert(
(function () {
delete users.Sarah;
return isEveryoneHere(users);
})() === false
);
```
関数 `isEveryoneHere` は、`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(userObj) {
// 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(userObj) {
return [
'Alan',
'Jeff',
'Sarah',
'Ryan'
].every(user => userObj.hasOwnProperty(user));
}
console.log(isEveryoneHere(users));
```

View File

@ -0,0 +1,63 @@
---
id: 587d7b7b367417b2b2512b17
title: スプレッド演算子による配列の結合
challengeType: 1
forumTopicId: 301156
dashedName: combine-arrays-with-the-spread-operator
---
# --description--
<dfn>スプレッド</dfn>演算子のもう一つの大きな利点は、配列を結合できること、つまり、ある配列のすべての要素を別の配列の任意のインデックスに挿入できることです。 従来の古い構文でも配列を結合できますが、その場合は、一方の末尾ともう一方の先頭の位置のみで結合が可能です。 スプレッド構文を使用すれば次のような操作が非常に簡単になります。
```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>スプレッド</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;
}
```

View File

@ -0,0 +1,102 @@
---
id: 587d7b7b367417b2b2512b13
title: スプレッド演算子による配列のコピー
challengeType: 1
forumTopicId: 301157
dashedName: copy-an-array-with-the-spread-operator
---
# --description--
`slice()` を使用すると、コピーする配列の要素を選択できますが、他にもいくつかの便利な機能があり、ES6の新しい<dfn>スプレッド演算子</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` (数値) を受け取ります。 この関数では、`arr``num` 個のコピーで構成される新しい配列を返す必要があります。 必要なものはほぼ揃っていますが、まだうまく機能しません。 スプレッド構文を使用して、正しく機能するように関数を変更してください (ヒント: すでに説明した別のメソッドがここで役に立つかもしれません)。
# --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));
```

View File

@ -0,0 +1,65 @@
---
id: 587d7b7a367417b2b2512b12
title: Slice() を使用した配列アイテムのコピー
challengeType: 1
forumTopicId: 301158
dashedName: copy-array-items-using-slice
---
# --description--
次に取り上げるメソッドは `slice()` です。 `slice()` は配列を変更するのではなく、指定された数の要素を新しい配列にコピー、または*抽出*します。呼び出された配列は変更されずに残されます。 `slice()` は 2 つのパラメーターしか取りません。最初のパラメーターは抽出を開始するインデックスで、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);
}
```

View File

@ -0,0 +1,218 @@
---
id: 587d7b7b367417b2b2512b16
title: 複雑な多次元配列の作成
challengeType: 1
forumTopicId: 301159
dashedName: create-complex-multi-dimensional-arrays
---
# --description--
お疲れ様! 配列について多くのことを学びましたね! かなりハイレベルな概要でしたが、配列の操作についてはまだ学ぶべきことがたくさんあります。その多くはこのあとのセクションで説明していきます。 ですが<dfn>オブジェクト</dfn>に移る前に、もう一度確認しておきましょう。これまでのチャレンジで取り上げたものより、配列をもう少し複雑にする方法について見ていきます。
配列をデータ構造として捉えるときに最も強力な機能の一つは、配列に他の配列を含めることができる、あるいは完全に他の配列で構成することができるという点です。 これまでのチャレンジでも、配列を含む配列を取り上げてきましたが、それらはかなり単純な例でした。 しかし、配列では他の配列を格納できる無限の深さの配列を扱うことができ、含まれる各配列にも任意のレベルの深さを持たせることができます。さらにそこに含まれる配列も同様です。 このように、配列はたちまち非常に複雑なデータ構造になる可能性があります。こうした配列のことを<dfn>多次元</dfn>配列、またはネストされた配列と呼びます。 以下の例を考えてみましょう。
```js
let nestedArray = [
['deep'],
[
['deeper'], ['deeper']
],
[
[
['deepest'], ['deepest']
],
[
[
['deepest-est?']
]
]
]
];
```
`deep` 配列はネストレベル 2 の深さです。 `deeper` 配列はレベル 3 の深さです。 `deepest` 配列はレベル 4、`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>文字列</dfn><dfn>数値</dfn><dfn>ブール値</dfn>を任意に組み合わせて使用し、ちょうどレベル 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` で、レベル 3 の深さの配列に、文字列 `deep` が 1 回だけ出現する必要があります。
```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` レベル 4 の深さの配列に、文字列 `deeper` が 1 回だけ出現する必要があります。
```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` で、レベル 5 の深さの配列に、文字列 `deepest` が 1 回だけ出現する必要があります。
```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']
];
```

View File

@ -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` のキーのみを含めます。
```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));
```

View File

@ -0,0 +1,138 @@
---
id: 587d7b7b367417b2b2512b15
title: For ループによる配列の全アイテムの繰り返し処理
challengeType: 1
forumTopicId: 301161
dashedName: iterate-through-all-an-arrays-items-using-for-loops
---
# --description--
配列処理では、必要な 1 つ以上の要素を検索したい場合や、特定の基準を満たすデータアイテムに基づいて配列を操作したい場合に、各アイテムを繰り返し処理できるととても便利です。 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` を受け取り、新しい配列を返します。 `elem` は、`arr` 内でネストされた 1 つ以上の配列の要素を表しますが、その要素が存在する場合もあれば存在しない場合もあります。 この関数を変更し、`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;
}
```

View File

@ -0,0 +1,152 @@
---
id: 587d7b7d367417b2b2512b1d
title: for...in ステートメントによるオブジェクトのキーの繰り返し処理
challengeType: 1
forumTopicId: 301162
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
---
# --description--
オブジェクト内のすべてのキーの繰り返し処理を必要とする場合があります。 これには、<dfn>for...in</dfn> ステートメントと呼ばれる JavaScript 固有の構文が必要になります。 `users` オブジェクトの場合は次のように記述できます。
```js
for (let user in users) {
console.log(user);
}
```
これは `Alan``Jeff``Sarah``Ryan` を出力し、それぞれの値を独自の行に表示します。
このステートメントでは変数 `user` を定義しました。ご覧のように、for...in ステートメントでオブジェクトがループ処理されるとき、この変数は繰り返し処理ごとにオブジェクトの各キーにリセットされ、それぞれのユーザー名がコンソールに出力されます。
**注:** オブジェクトも配列の場合と同じように、格納されているキーの順序は維持されません。つまり、キーを参照したりキーにアクセスしたりするときは、そのキーのオブジェクト内での位置や、表示される相対的な順序は無関係になります。
# --instructions--
関数 `countOnline` を定義しました。この関数は 1 つの引数 (ユーザーオブジェクト) を受け取ります。 この関数の中で <dfn>for...in</dfn> ステートメントを使用して、関数に渡されたユーザーオブジェクトをループ処理し、`online` プロパティが `true` に設定されているユーザーの数を返してください。 たとえば、`countOnline` には次のようなユーザーオブジェクトが渡されます。 各ユーザーは `true` または `false` のいずれかの値を持つ `online` プロパティを持ちます。
```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*\)/
)
);
```
関数 `countOnline` は、オブジェクト `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` が渡された場合、`1` を返す必要があります。
```js
assert(countOnline(usersObj1) === 1);
```
関数 `countOnline` は、オブジェクト `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` が渡された場合、`2` を返す必要があります。
```js
assert(countOnline(usersObj2) === 2);
```
関数 `countOnline` は、オブジェクト `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` が渡された場合、`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
const users = {
Alan: {
online: false
},
Jeff: {
online: true
},
Sarah: {
online: false
}
}
function countOnline(usersObj) {
// Only change code below this line
// Only change code above this line
}
console.log(countOnline(users));
```
# --solutions--
```js
function countOnline(usersObj) {
let online = 0;
for(let user in usersObj){
if(usersObj[user].online) {
online++;
}
}
return online;
}
```

View File

@ -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> オブジェクトについても取り上げています。どちらも通常のオブジェクトと似ていますが、いくつかの追加機能を備えています。 配列やオブジェクトの基本を学んできたことで、JavaScript を使用したより複雑な問題に取り組む準備が整いました。
# --instructions--
コードエディターに用意されているオブジェクトをご覧ください。 この `user` オブジェクトには 3 つのキーが含まれています。 `data` キーには 5 つのキーが含まれており、そのうちの 1 つには `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` の配列に friend を追加する必要があります。
```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;
}
```

View File

@ -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` には、`id` (値は数値)、`date` (値は文字列)、`data` (値はネスト構造のオブジェクト) の 3 つのプロパティがあります。 構造はすぐに複雑になりますが、同じ記法を使用して、必要な情報にアクセスすることができます。 ネストされた `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;
```

View File

@ -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()` と違って、どちらのメソッドもパラメーターを受け取らず、一度に 1 つの配列要素しか変更できません。
以下を見てみましょう。
```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];
}
```

View File

@ -0,0 +1,87 @@
---
id: 587d78b2367417b2b2512b10
title: Splice() によるアイテムの削除
challengeType: 1
forumTopicId: 301166
dashedName: remove-items-using-splice
---
# --description--
`shift()``pop()` を使用して、配列の先頭と末尾から要素を削除する方法を学びました。しかし中間のどこかから要素を取り除きたい場合はどうすればよいでしょうか? あるいは、一度に複数の要素を取り除きたい場合はどうすればよいでしょうか? そこで登場するのが `splice()` です。 `splice()` を使用すると、配列の任意の場所から**連続した任意の数の要素を削除する**ことができます。
`splice()` は最大で 3 つのパラメーターを受け取ることができますが、ここでは最初の 2 つだけに注目しましょう。 `splice()` の最初の 2 つのパラメーターは、`splice()` を呼び出している配列のインデックス (または位置) を表す整数です。 すでに説明したように、配列は*インデックスがゼロから始まる*ため、配列の最初の要素を指定する場合は `0` を使用します。 `splice()` の最初のパラメーターは、要素の削除を開始する配列上のインデックスを表します。 一方、2 番目のパラメータは、削除する要素の数を示します。 例:
```js
let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2);
```
ここでは、3 番目の要素 (インデックスが 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);
```

View File

@ -0,0 +1,95 @@
---
id: 587d7b7e367417b2b2512b20
title: 配列によって複数のデータをまとめて格納する
challengeType: 1
forumTopicId: 301167
dashedName: use-an-array-to-store-a-collection-of-data
---
# --description--
以下は、配列データ構造の最も簡単な実装例です。 このような配列を <dfn>1 次元配列</dfn>と呼びます。つまり、1 つの階層しか持たない、あるいは内部にネストされた他の配列がない配列です。 <dfn>ブール値</dfn><dfn>文字列</dfn><dfn>数値</dfn>など、JavaScript の有効な他のデータ型が含まれていることに注意してください。
```js
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
console.log(simpleArray.length);
```
この `console.log``7` を表示します。
すべての配列には上記のような length プロパティがあり、`Array.length` という構文で非常に簡単にアクセスできます。 もっと複雑な配列の実装例を以下に示します。 こうした配列を<dfn>多次元配列</dfn>と呼びます。つまり、他の配列を含む配列です。 この配列には JavaScript の<dfn>オブジェクト</dfn>も含まれていることに注意してください。オブジェクトについては次のセクションで詳しく説明します。 しかしここでは、配列は複雑なオブジェクトも格納できるということだけを知っておいてください。
```js
let complexArray = [
[
{
one: 1,
two: 2
},
{
three: 3,
four: 4
}
],
[
{
a: "a",
b: "b"
},
{
c: "c",
d: "d"
}
]
];
```
# --instructions--
`yourArray` という変数を定義しました。 `yourArray` 変数に、要素数 length が 5 以上の配列を割り当てて、記述を完成させてください。 配列には<dfn>文字列</dfn><dfn>数値</dfn><dfn>ブール値</dfn>をそれぞれ 1 つ以上含める必要があります。
# --hints--
`yourArray` は配列である必要があります。
```js
assert.strictEqual(Array.isArray(yourArray), true);
```
`yourArray` の要素数は 5 以上である必要があります。
```js
assert.isAtLeast(yourArray.length, 5);
```
`yourArray` には少なくとも 1 つの `boolean` を含める必要があります。
```js
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
```
`yourArray` には少なくとも 1 つの `number` を含める必要があります。
```js
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
```
`yourArray` には少なくとも 1 つの `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'];
```

View File

@ -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` オブジェクトには `apples``grapes``bananas` の 3 つのキーのみが存在する必要があります。
```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);
```

View File

@ -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>インデックス</dfn>を使用して配列内のデータにアクセスすることができます。
配列インデックスは文字列と同じくブラケット記法で記述します。異なっているのは、文字の代わりに配列内のエントリを指定する点です。 文字列と同様に、配列では <dfn>0 から始まる</dfn>インデックスを使用するため、配列の最初の要素のインデックスは `0` になります。
<br>
**例**
```js
const array = [50, 60, 70];
array[0];
const 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
const myArray = [50, 60, 70];
```
# --solutions--
```js
const myArray = [50, 60, 70];
const myData = myArray[0];
```

View File

@ -0,0 +1,77 @@
---
id: 56592a60ddddeae28f7aa8e1
title: インデックスによる多次元配列へのアクセス
challengeType: 1
videoUrl: 'https://scrimba.com/c/ckND4Cq'
forumTopicId: 16159
dashedName: access-multi-dimensional-arrays-with-indexes
---
# --description--
<dfn>多次元</dfn>配列は、*配列の配列*として考えることができます。 ブラケット (角括弧) を使用して配列にアクセスする場合、最初のブラケットのセットは、一番外側 (最初の階層) の配列の項目を参照します。 ブラケットを追加するたびに、その次の階層の項目を参照します。
**例**
```js
const 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--
ブラケット記法を使用して、`myData``8` に等しくなるように、`myArray` から要素を取得してください。
# --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
const myArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[[10, 11, 12], 13, 14],
];
const myData = myArray[0][0];
```
# --solutions--
```js
const myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[10, 11, 12], 13, 14]];
const myData = myArray[2][1];
```

View File

@ -0,0 +1,121 @@
---
id: 56533eb9ac21ba0edf2244cd
title: ネストされた配列へのアクセス
challengeType: 1
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
forumTopicId: 16160
dashedName: accessing-nested-arrays
---
# --description--
これまでの例で見てきたとおり、オブジェクトには、ネストされたオブジェクトとネストされた配列のどちらも含めることができます。 ネストされたオブジェクトへのアクセスと同様に、配列のブラケット記法のチェーンを使用して、ネストされた配列にアクセスできます。
次はネストされた配列にアクセスする方法の例です。
```js
const 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--
ドット記法とブラケット記法を使用して、変数 `secondTree``myPlants` オブジェクトの `trees` リストの 2 番目のアイテムとなるように設定してください。
# --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
const myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
const secondTree = "";
```
# --solutions--
```js
const myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
const secondTree = myPlants[1].list[1];
```

View File

@ -0,0 +1,100 @@
---
id: 56533eb9ac21ba0edf2244cc
title: ネストされたオブジェクトへのアクセス
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRnRnfa'
forumTopicId: 16161
dashedName: accessing-nested-objects
---
# --description--
オブジェクトの下位プロパティには、ドット記法またはブラケット記法によるチェーンでアクセスできます。
次はネストされたオブジェクトです。
```js
const 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
const myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
const gloveBoxContents = undefined;
```
# --solutions--
```js
const myStorage = {
"car":{
"inside":{
"glove box":"maps",
"passenger seat":"crumbs"
},
"outside":{
"trunk":"jack"
}
}
};
const gloveBoxContents = myStorage.car.inside["glove box"];
```

View File

@ -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--
オブジェクトのプロパティにアクセスする 2 つ目の方法は、ブラケット記法 (`[]`) です。 アクセスしようとしているオブジェクトのプロパティの名前にスペースが含まれている場合は、ブラケット記法を使用する必要があります。
ただし、オブジェクトのプロパティにスペースが含まれていない場合もブラケット記法を使用できます。
次は、ブラケット記法を使用してオブジェクトのプロパティを読み取る例です。
```js
const 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');
```
ブラケット記法を 2 回使用する必要があります。
```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
const testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
// Only change code below this line
const entreeValue = testObj; // Change this line
const drinkValue = testObj; // Change this line
```
# --solutions--
```js
const testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
const entreeValue = testObj["an entree"];
const drinkValue = testObj['the drink'];
```

View File

@ -0,0 +1,100 @@
---
id: 56533eb9ac21ba0edf2244c7
title: ドット記法によるオブジェクトのプロパティへのアクセス
challengeType: 1
videoUrl: 'https://scrimba.com/c/cGryJs8'
forumTopicId: 16164
dashedName: accessing-object-properties-with-dot-notation
---
# --description--
配列の場合と同様に、オブジェクトのプロパティへのアクセス方法も、ドット記法 (`.`) とブラケット記法 (`[]`) の 2 通りがあります。
ドット記法は、アクセスしようとしているプロパティの名前があらかじめわかっている場合に使用します。
次は、ドット記法 (`.`) を使用してオブジェクトのプロパティを読み取る例です。
```js
const myObj = {
prop1: "val1",
prop2: "val2"
};
const prop1val = myObj.prop1;
const 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');
```
ドット記法を 2 回使用する必要があります。
```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
const testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
// Only change code below this line
const hatValue = testObj; // Change this line
const shirtValue = testObj; // Change this line
```
# --solutions--
```js
const testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
const hatValue = testObj.hat;
const shirtValue = testObj.shirt;
```

View File

@ -0,0 +1,125 @@
---
id: 56533eb9ac21ba0edf2244c9
title: 変数によるオブジェクトのプロパティへのアクセス
challengeType: 1
videoUrl: 'https://scrimba.com/c/cnQyKur'
forumTopicId: 16165
dashedName: accessing-object-properties-with-variables
---
# --description--
オブジェクトに対するブラケット記法のもう一つの用例として、プロパティを変数の値として保存し、アクセスする方法があります。 この用法は、オブジェクトのプロパティを繰り返し処理する場合や、ルックアップテーブルにアクセスする場合にとても便利です。
次は変数を使用してプロパティにアクセスする例です。
```js
const dogs = {
Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"
};
const myDog = "Hunter";
const myBreed = dogs[myDog];
console.log(myBreed);
```
コンソールには文字列 `Doberman` が表示されます。
この用法の別の例として、プログラムの実行中にプロパティの名前を動的に取得することができます。次に例を示します。
```js
const someObj = {
propName: "John"
};
function propPrefix(str) {
const s = "prop";
return s + str;
}
const 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
const testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
// Only change code below this line
const playerNumber = 42; // Change this line
const player = testObj; // Change this line
```
# --solutions--
```js
const testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
const playerNumber = 16;
const player = testObj[playerNumber];
```

View File

@ -0,0 +1,90 @@
---
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
const ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
ourDog.bark = "bow-wow";
```
# --instructions--
`myDog``bark` プロパティを追加して、"woof" などの犬の鳴き声を設定してください。 ドット記法またはブラケット記法のいずれも使用できます。
# --hints--
プロパティ `bark``myDog` に追加する必要があります。
```js
assert(myDog.bark !== undefined);
```
`myDog` の初期化に `bark`を追加しないでください。
```js
assert(!/bark[^\n]:/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(z){return z;})(myDog);
```
## --seed-contents--
```js
const myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
```
# --solutions--
```js
const myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
myDog.bark = "Woof Woof";
```

View File

@ -0,0 +1,62 @@
---
id: cf1111c1c11feddfaeb3bdef
title: JavaScript で 2 つの数値を足し算する
challengeType: 1
videoUrl: 'https://scrimba.com/c/cM2KBAG'
forumTopicId: 16650
dashedName: add-two-numbers-with-javascript
---
# --description--
`Number` は数値データを表す JavaScript のデータ型です。
では、JavaScript で 2 つの数字の足し算をしてみましょう。
JavaScript では `+` 記号を加算演算子として 2 つの数字の間に置いて使用します。
**例:**
```js
const myVar = 5 + 10;
```
`myVar` の値はいま `15` になりました。
# --instructions--
`0` を、和が `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
const sum = 10 + 0;
```
# --solutions--
```js
const sum = 10 + 10;
```

View File

@ -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` ステートメントとして指定することができない場合があります。 代わりに、`case` に一致するものが見つからない場合に実行される `default` を追加することができます。 これは、`if/else` チェーンの最後の `else` のようなものだと考えてください。
`default` ステートメントは最後の case として記述してください。
```js
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
```
# --instructions--
次の条件ごとに `answer` を設定した switch ステートメントを記述してください。
`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) {
let answer = "";
// Only change code below this line
// Only change code above this line
return answer;
}
switchOfStuff(1);
```
# --solutions--
```js
function switchOfStuff(val) {
let answer = "";
switch(val) {
case "a":
answer = "apple";
break;
case "b":
answer = "bird";
break;
case "c":
answer = "cat";
break;
default:
answer = "stuff";
}
return answer;
}
```

View File

@ -0,0 +1,77 @@
---
id: 56533eb9ac21ba0edf2244ed
title: 文字列への変数の連結
challengeType: 1
videoUrl: 'https://scrimba.com/c/cbQmZfa'
forumTopicId: 16656
dashedName: appending-variables-to-strings
---
# --description--
複数行の文字列<dfn>リテラル</dfn>から文字列を作成することができますが、それと同じように、加算代入 (`+=`) 演算子を使用して変数を文字列に連結することができます。
例:
```js
const anAdjective = "awesome!";
let ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
```
`ourStr` の値は `freeCodeCamp is awesome!` となります。
# --instructions--
`someAdjective` に 3 文字以上の文字列を設定し、`+=` 演算子を使用して `myStr` に連結してください。
# --hints--
`someAdjective` には 3 文字以上の長さの文字列を設定する必要があります。
```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
const someAdjective = "";
let myStr = "Learning to code is ";
```
# --solutions--
```js
const someAdjective = "neat";
let myStr = "Learning to code is ";
myStr += someAdjective;
```

View File

@ -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;
```

View File

@ -0,0 +1,72 @@
---
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)で説明したように、等号の右側の部分はすべて、値が代入される前に解決されます。 つまり、関数の戻り値を受け取って変数に代入することができます。
2 つの数値を足し算する関数 `sum` があらかじめ定義されているとします。次の
```js
ourSum = sum(5, 12);
```
`sum` 関数を呼び出します。関数は `17` という値を返し、その値が `ourSum` 変数に代入されます。
# --instructions--
`7` を引数に取る `processArg` 関数を呼び出し、その戻り値を変数 `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
let 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);
```

View File

@ -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
const cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
```
この例では、すべてのプロパティを `name``legs``tails` のように文字列として格納しています。 しかし、数値もプロパティとして使用することが可能です。 次のように、1 つの単語の文字列プロパティの場合は引用符を省略することもできます。
```js
const 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
const myDog = {
// Only change code below this line
// Only change code above this line
};
```
# --solutions--
```js
const myDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
```

View File

@ -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";
}
}
```

View File

@ -0,0 +1,63 @@
---
id: bd7123c9c441eddfaeb4bdef
title: JavaScript コードにコメントする
challengeType: 1
removeComments: false
videoUrl: 'https://scrimba.com/c/c7ynnTp'
forumTopicId: 16783
dashedName: comment-your-javascript-code
---
# --description--
コメントとは、JavaScript が意図的にコードを無視する行です。 コメントは、そのコードが何をするかを後で自分自身や他の人が把握するためにメモを残すために最適な方法です。
JavaScript でコメントを書く方法は 2 つあります。
`//` を使用すると、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 */
```

View File

@ -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` を返します。
最も基本的な演算子は等価演算子 `==` です。 等価演算子は 2 つの値を比較し、等価な場合は `true` を、そうでない場合は `false` を返します。 等価は代入 (`=`) とは異なることに注意してください。代入は演算子の右側の値を左側の変数に割り当てるものです。
```js
function equalityTest(myVal) {
if (myVal == 10) {
return "Equal";
}
return "Not Equal";
}
```
`myVal``10` と等しい場合には、等価演算子は `true` を返し、中括弧内のコードが実行されて、関数は `Equal` を返します。 それ以外の場合、関数は `Not Equal` を返します。 JavaScript では、比較する 2 つのデータの<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";
}
```

View File

@ -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--
大なり演算子 (`>`) は、2 つの数値の値を比較します。 左の数値が右の数値よりも大きい場合は、`true` を返します。 それ以外の場合は、`false` を返します。
等価演算子と同様に、大なり演算子でも比較時に値のデータ型が変換されます。
**例**
```js
5 > 3
7 > '3'
2 > 3
'1' > 9
```
これらの式は上から順に、`true``true``false``false` と評価されます。
# --instructions--
return ステートメントの意味が正しくなるように、指定された行に大なり演算子を追加してください。
# --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');
```
`>` 演算子を 2 回以上使用してください。
```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";
}
```

View File

@ -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--
大なりイコール演算子 (`>=`) は、2 つの数値の値を比較します。 左の数値が右の数値よりも大きいか等しい場合は、`true` を返します。 それ以外の場合は、`false` を返します。
等価演算子と同様に、大なりイコール演算子でも比較時にデータ型が変換されます。
**例**
```js
6 >= 6
7 >= '3'
2 >= 3
'7' >= 9
```
これらの式は上から順に、`true``true``false``false` と評価されます。
# --instructions--
return ステートメントの意味が正しくなるように、指定された行に大なりイコール演算子を追加してください。
# --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');
```
`>=` 演算子を 2 回以上使用してください。
```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";
}
```

View File

@ -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--
`val``99` と等しくない場合に関数が文字列 `Not Equal` を返すように、`if` ステートメントに不等価演算子 `!=` を追加してください。
# --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";
}
```

View File

@ -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--
小なり演算子 (`<`) は、2 つの数値の値を比較します。 左の数値が右の数値よりも小さい場合は、`true` を返します。 それ以外の場合は、`false` を返します。 等価演算子と同様に、小なり演算子でも比較時にデータ型が変換されます。
**例**
```js
2 < 5
'3' < 7
5 < 5
3 < 2
'8' < 4
```
これらの式は上から順に、`true``true``false``false``false` と評価されます。
# --instructions--
return ステートメントの意味が正しくなるように、指定された行に小なり演算子を追加してください。
# --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');
```
`<` 演算子を 2 回以上使用してください。
```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";
}
```

View File

@ -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--
小なりイコール演算子 (`<=`) は、2 つの数値の値を比較します。 左の数値が右の数値よりも小さいか等しい場合は、`true` を返します。 左の数値が右の数値よりも大きい場合は、`false` を返します。 等価演算子と同様に、小なりイコール演算子でもデータ型が変換されます。
**例**
```js
4 <= 5
'7' <= 7
5 <= 5
3 <= 2
'8' <= 4
```
これらの式は上から順に、`true``true``true``false``false` と評価されます。
# --instructions--
return ステートメントの意味が正しくなるように、指定された行に小なりイコール演算子を追加してください。
# --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');
```
`<=` 演算子を 2 回以上使用してください。
```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";
}
```

View File

@ -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``false` を返すことになります。
2 番目の例では、 `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";
}
```

View File

@ -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--
`val``17` と厳密に等しくない場合に関数が文字列 `Not Equal` を返すように、`if` ステートメントに厳密不等価演算子を追加してください。
# --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";
}
```

View File

@ -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>演算子 (`&&`) は、左側と右側の<dfn>オペランド</dfn>の両方が true である場合にのみ `true` を返します。
if ステートメントを別の 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--
`&&` 演算子を使用して、2つの if ステートメントを 1 つのステートメントにしてください。このプログラムは `val``25` 以上 `50` 以下の場合に文字列 `Yes` を返します。 それ以外の場合は文字列 `No` を返します。
# --hints--
`&&` 演算子を 1 回使用してください。
```js
assert(code.match(/&&/g).length === 1);
```
`if` ステートメントを 1 つだけにする必要があります。
```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";
}
```

View File

@ -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>演算子は 2 本のパイプ記号 (`||`) で構成されます。 この記号のキーは通常、バックスペースキーと Enter キーの間近くにあります。
次のようなパターンは以前のチャレンジでも登場しています。
```js
if (num > 10) {
return "No";
}
if (num < 5) {
return "No";
}
return "Yes";
```
上の例は、`num``5``10` の間 (5 と 10 を含む) の場合のみ、`Yes` を返します。 同じロジックを次のように記述することができます。
```js
if (num > 10 || num < 5) {
return "No";
}
return "Yes";
```
# --instructions--
2つの `if` ステートメントを 1 つのステートメントにまとめて、`val``10` 以上 `20` 以下でない場合は文字列 `Outside` を返すようにしてください。 それ以外の場合は、文字列 `Inside` を返してください。
# --hints--
`||`演算子を 1 回使用してください。
```js
assert(code.match(/\|\|/g).length === 1);
```
`if` ステートメントを 1 つだけにする必要があります。
```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";
}
```

View File

@ -0,0 +1,101 @@
---
id: 56533eb9ac21ba0edf2244af
title: 加算と代入の組み合わせ
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDR6LCb'
forumTopicId: 16661
dashedName: compound-assignment-with-augmented-addition
---
# --description--
プログラミングでは、代入を使用して変数の中身を変更する操作がよく行われます。 最初に等号の右辺のすべてが評価されることを忘れないようにしましょう。
```js
myVar = myVar + 5;
```
と記述すると、`myVar``5` を足すことができます。 このような操作は一般的なパターンなので、算術演算と代入の両方を一度に行う演算子があります。
その一つが `+=` 演算子です。
```js
let 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(
/let a = 3;/.test(code) &&
/let b = 17;/.test(code) &&
/let 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
let a = 3;
let b = 17;
let c = 12;
// Only change code below this line
a = a + 12;
b = 9 + b;
c = c + 7;
```
# --solutions--
```js
let a = 3;
let b = 17;
let c = 12;
a += 12;
b += 9;
c += 7;
```

View File

@ -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(
/let a = 48;/.test(code) &&
/let b = 108;/.test(code) &&
/let 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
let a = 48;
let b = 108;
let c = 33;
// Only change code below this line
a = a / 12;
b = b / 4;
c = c / 11;
```
# --solutions--
```js
let a = 48;
let b = 108;
let c = 33;
a /= 12;
b /= 4;
c /= 11;
```

View File

@ -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(
/let a = 5;/.test(code) &&
/let b = 12;/.test(code) &&
/let 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
let a = 5;
let b = 12;
let c = 4.6;
// Only change code below this line
a = a * 5;
b = 3 * b;
c = c * 10;
```
# --solutions--
```js
let a = 5;
let b = 12;
let c = 4.6;
a *= 5;
b *= 3;
c *= 10;
```

View File

@ -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(
/let a = 11;/.test(code) && /let b = 9;/.test(code) && /let 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
let a = 11;
let b = 9;
let c = 3;
// Only change code below this line
a = a - 6;
b = b - 15;
c = c - 1;
```
# --solutions--
```js
let a = 11;
let b = 9;
let c = 3;
a -= 6;
b -= 15;
c -= 1;
```

View File

@ -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
const ourStr = "I come first. " + "I come second.";
```
文字列 `I come first. ` `I come second.` がコンソールに表示されます。
# --instructions--
`+` 演算子を使用して、文字列 `This is the start.``This is the end.` から `myStr` を作成してください。 2 つの文字列の間に空白を必ず含めるようにしてください。
# --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));
```
`const` キーワードを使用して `myStr` を作成する必要があります。
```js
assert(/const\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
const myStr = ""; // Change this line
```
# --solutions--
```js
const myStr = "This is the start. " + "This is the end.";
```

View File

@ -0,0 +1,68 @@
---
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
let 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.` の 2 つの文字列を連結し、複数行にわたる `myStr` を作成してください。 前の例のように、`+=` 演算子を使用し、必ず 2 つの文字列の間に空白を入れてください。 まず `myStr` に 1 つ目の文字列を代入し、それから 2 つ目の文字列を追加してください。
# --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
let myStr;
```
# --solutions--
```js
let myStr = "This is the first sentence. ";
myStr += "This is the second sentence.";
```

View File

@ -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) 的に文字列を作成しなければならない場合があります。 連結演算子 (`+`) を使用して、作成する文字列に 1 つまたは複数の変数を挿入することができます。
例:
```js
const ourName = "freeCodeCamp";
const ourStr = "Hello, our name is " + ourName + ", how are you?";
```
`ourStr` の値は文字列 `Hello, our name is freeCodeCamp, how are you?` となります。
# --instructions--
`myName` にあなたの名前と同じ文字列を設定し、文字列 `My name is``and I am well!` の間に `myName` を挿入した `myStr` を作成してください。
# --hints--
`myName` には 3 文字以上の長さの文字列を設定する必要があります。
```js
assert(typeof myName !== 'undefined' && myName.length > 2);
```
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
const myName = "";
const myStr = "";
```
# --solutions--
```js
const myName = "Bob";
const myStr = "My name is " + myName + " and I am well!";
```

View File

@ -0,0 +1,77 @@
---
id: 56105e7b514f539506016a5e
title: for ループでの減算
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2R6BHa'
forumTopicId: 16808
dashedName: count-backwards-with-a-for-loop
---
# --description--
for ループでは、適切な条件を定義することができれば、減算も可能です。
繰り返しごとに 2 ずつデクリメント (減算) するには、初期化式、条件式、および最終式を変更する必要があります。
`i = 10` から始めて、`i > 0` の間、ループ処理を行います。 `i -= 2` と記述すると、ループごとに `i` が 2 ずつデクリメントされます。
```js
const ourArray = [];
for (let i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
```
`ourArray` の内容は `[10, 8, 6, 4, 2]` になります。 2 ずつ減算して奇数の降順の配列を作成できるように、初期化式と最終式を変更してみましょう。
# --instructions--
`for` ループを使用して、9 から 1 までの奇数を `myArray` に push してください。
# --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
const myArray = [];
// Only change code below this line
```
# --solutions--
```js
const myArray = [];
for (let i = 9; i > 0; i -= 2) {
myArray.push(i);
}
```

View File

@ -0,0 +1,201 @@
---
id: 565bbe00e9cc8ac0725390f4
title: カードカウンティング
challengeType: 1
videoUrl: 'https://scrimba.com/c/c6KE7ty'
forumTopicId: 16809
dashedName: counting-cards
---
# --description--
カジノゲームのブラックジャックでは、デッキに残っているカードのハイローの相対数を把握しておくことで、プレイヤーはディーラーに対して有利な立場を得られます。 これは[カードカウンティング](https://en.wikipedia.org/wiki/Card_counting)と呼ばれています。
デッキに残っているハイカードの数が多いほど、プレイヤーに有利となります。 次の表に従って各カードに値を割り当てます。 カウンティングの結果が正の場合、プレイヤーは高く賭けるべきです。 カウンティングの結果がゼロまたは負の場合、プレイヤーは少なめに賭けた方がいいでしょう。
<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>
カードカウンティング関数を記述してください。 この関数は数値または文字列の `card` パラメーターを受け取り、カードの値に応じて (表を参照)、グローバルの `count` 変数をインクリメントまたはデクリメントします。 次に、この関数は現在のカウントを示す文字列と、文字列 `Bet` (カウントが正の場合) または文字列 `Hold` (カウントがゼロか負の場合) を返します。 現在のカウントとプレイヤーの判断 (`Bet` または `Hold`) の間にスペースを 1 つ入れてください。
**出力例:** `-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
let 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
let 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";
}
}
```

View File

@ -0,0 +1,55 @@
---
id: cf1391c1c11feddfaeb4bdef
title: JavaScript で小数を作成する
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8GEuW'
forumTopicId: 16826
dashedName: create-decimal-numbers-with-javascript
---
# --description--
変数に小数を格納することもできます。 小数は<dfn>浮動小数点数</dfn>または <dfn>float</dfn> と呼ばれることもあります。
**注:** すべての実数を正確に<dfn>浮動小数点数</dfn>で表すことができるわけではありません。 これは丸めエラーをもたらす可能性があります。 詳細は[こちら](https://en.wikipedia.org/wiki/Floating-point_arithmetic#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
const ourDecimal = 5.7;
// Only change code below this line
```
# --solutions--
```js
const myDecimal = 9.9;
```

View File

@ -0,0 +1,88 @@
---
id: 587d7b87367417b2b2512b41
title: const キーワードを使用して読み取り専用の変数を宣言する
challengeType: 1
forumTopicId: 301201
dashedName: declare-a-read-only-variable-with-the-const-keyword
---
# --description--
変数を宣言する新しい方法はキーワード `let` だけではありません。 ES6 では、`const` キーワードを使用して変数を宣言することもできます。
`const``let` の持つ素晴らしい機能をすべて備えていますが、それだけでなく、`const` を使用して宣言した変数は読み取り専用になります。 それらの変数は定数となり、いったん `const` で代入された変数には、再び代入することはできません。
```js
const FAV_PET = "Cats";
FAV_PET = "Dogs";
```
`FAV_PET` に再び値を代入しようとしているので、コンソールにエラーが表示されます。
再代入を必要としない変数に名前を付けるときは、常に `const` キーワードを使用してください。 そうすれば、定数でなければならない変数に誤って再代入しようとするのを防ぐのに役立ちます。
一般に、定数に名前を付けるときは、すべて英大文字を使用し、単語をアンダースコアで区切ります。
**注:** 開発者は一般に、イミュータブル (変更不可) の値には英大文字の変数識別子を使用し、ミュータブル (変更可能) の値 (オブジェクトや配列) には英小文字またはキャメルケースを使用します。 このあとのチャレンジで、オブジェクトと配列について学び、ミュータブルの値とイミュータブルの値について詳しく説明します。 また以降のチャレンジでは、英大文字、英小文字、またはキャメルケースのさまざまな変数識別子を使用します。
# --instructions--
コードを変更して、すべての変数を `let` または `const` を使用して宣言してください。 変更を必要とする変数には `let` を使用し、定数にする必要がある変数には `const` を使用してください。 また、`const` で宣言した変数の名前について、すべて英大文字にするという一般的な慣習に従うように変更してください。
# --hints--
`var` がコード内に存在しない必要があります。
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
`fCC` をすべて英大文字に変更する必要があります。
```js
(getUserInput) => {
assert(getUserInput('index').match(/(FCC)/));
assert(!getUserInput('index').match(/fCC/));
}
```
`FCC``const` で宣言された定数変数である必要があります。
```js
assert.equal(FCC, 'freeCodeCamp');
assert.match(code, /const\s+FCC/);
```
`fact``let` を使用して宣言する必要があります。
```js
(getUserInput) => assert(getUserInput('index').match(/(let fact)/g));
```
`console.log` を、`FCC``fact` 変数を出力するように変更する必要があります。
```js
(getUserInput) =>
assert(getUserInput('index').match(/console\.log\(\s*FCC\s*\,\s*fact\s*\)\s*;?/g));
```
# --seed--
## --seed-contents--
```js
var fCC = "freeCodeCamp"; // Change this line
var fact = "is cool!"; // Change this line
fact = "is awesome!";
console.log(fCC, fact); // Change this line
```
# --solutions--
```js
const FCC = "freeCodeCamp";
let fact = "is cool!";
fact = "is awesome!";
console.log(FCC, fact);
```

View File

@ -0,0 +1,61 @@
---
id: bd7123c9c443eddfaeb5bdef
title: JavaScript 変数を宣言する
challengeType: 1
videoUrl: 'https://scrimba.com/c/cNanrHq'
forumTopicId: 17556
dashedName: declare-javascript-variables
---
# --description--
コンピューターサイエンスでは、<dfn>データ</dfn>とはコンピューターにとって意味のある情報のことです。 JavaScript では 8 つの異なる<dfn>データ型</dfn>として、`undefined``null``boolean``string``symbol``bigint``number``object` が提供されています。
たとえば、コンピューターでは `12` などの数値と、`"12"``"dog"``"123 cats"` といった文字の集まりである `strings` (文字列) が区別されます。 コンピューターは数値に対して数学演算を実行することができますが、文字列に対してそれを実行することはできません。
<dfn>変数</dfn>を使用すると、コンピューターがデータを動的に格納して操作することが可能になります。 その際、データ自体が使用されるのではなく、データを指し示す「ラベル」が使用されます。 8 つのデータ型はどれも変数に格納することができます。
変数は、数学で使用される x や y といった変数と似ています。つまり、これらは参照したいデータを表す名前にすぎません。 コンピューターの変数は数学の変数とは異なり、さまざまな値をさまざまなタイミングで格納することができます。
JavaScript で変数を作成または<dfn>宣言</dfn>するには、次のように変数の前に `var` キーワードを付けます。
```js
var ourName;
```
これで `ourName` という変数が作成されます。 JavaScript では、ステートメントの終わりにセミコロンを付けます。 変数名には、数字、文字、`$`、または `_` を使用できます。 ただし、スペースを含めることはできず、数字で名前を始めることはできません。
# --instructions--
`var` キーワードを使用して `myName` という変数を作成してください。
**ヒント**
わからない場合は上の `ourName` の例を見てください。
# --hints--
`myName``var` キーワードで宣言し、末尾にセミコロンを付ける必要があります。
```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;
```

View File

@ -0,0 +1,87 @@
---
id: bd7123c9c444eddfaeb5bdef
title: 文字列変数を宣言する
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2QvWU6'
forumTopicId: 17557
dashedName: declare-string-variables
---
# --description--
前回は次のコードを使用して変数を宣言しました。
```js
var myName;
```
しかし、次のように文字列変数を宣言することもできます。
```js
var myName = "your name";
```
こうした `"your name"` のような文字列のことを<dfn>文字列</dfn><dfn>リテラル</dfn>と呼びます。 文字列リテラル (単に文字列とも呼びます) は、シングルクォートまたはダブルクォートで囲まれた 0 文字以上の一連の文字です。
# --instructions--
2 つの新しい文字列変数 `myFirstName``myLastName` を作成し、それらにあなたの名前と苗字をそれぞれ代入してください。
# --hints--
`myFirstName` は少なくとも 1 つの文字を含む文字列である必要があります。
```js
assert(
(function () {
if (
typeof myFirstName !== 'undefined' &&
typeof myFirstName === 'string' &&
myFirstName.length > 0
) {
return true;
} else {
return false;
}
})()
);
```
`myLastName` はは少なくとも 1 つの文字を含む文字列である必要があります。
```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";
```

View File

@ -0,0 +1,80 @@
---
id: 56533eb9ac21ba0edf2244ad
title: JavaScript で数値をデクリメントする
challengeType: 1
videoUrl: 'https://scrimba.com/c/cM2KeS2'
forumTopicId: 17558
dashedName: decrement-a-number-with-javascript
---
# --description--
`--` 演算子を使用して簡単に変数の値を 1 減らす (<dfn>デクリメント</dfn>する) ことができます。
```js
i--;
```
は次の式と等価です。
```js
i = i - 1;
```
**注:** この行全体が `i--;` となり、等号が不要になります。
# --instructions--
コードを変更して `myVar``--` 演算子を使用してください。
# --hints--
`myVar``10` に等しくなる必要があります。
```js
assert(myVar === 10);
```
`myVar = myVar - 1;` を書き換える必要があります。
```js
assert(
/let\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(/let myVar = 11;/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(z){return 'myVar = ' + z;})(myVar);
```
## --seed-contents--
```js
let myVar = 11;
// Only change code below this line
myVar = myVar - 1;
```
# --solutions--
```js
let myVar = 11;
myVar--;
```

View File

@ -0,0 +1,96 @@
---
id: 56bbb991ad1ed5201cd392d3
title: JavaScript オブジェクトからのプロパティの削除
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDqKdTv'
forumTopicId: 17560
dashedName: delete-properties-from-a-javascript-object
---
# --description--
次のようにオブジェクトからプロパティを削除することもできます。
```js
delete ourDog.bark;
```
例:
```js
const 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--
`tails` プロパティを `myDog` から削除してください。 ドット記法またはブラケット記法のいずれも使用できます。
# --hints--
プロパティ `tails``myDog` から削除する必要があります。
```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
const myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"],
"bark": "woof"
};
// Only change code below this line
```
# --solutions--
```js
const myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"],
"bark": "woof"
};
delete myDog.tails;
```

View File

@ -0,0 +1,56 @@
---
id: bd7993c9ca9feddfaeb7bdef
title: JavaScript で小数どうしの割り算をする
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.0 で割る必要があります。
```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
const quotient = 0.0 / 2.0; // Change this line
```
# --solutions--
```js
const quotient = 4.4 / 2.0;
```

View File

@ -0,0 +1,59 @@
---
id: cf1111c1c11feddfaeb6bdef
title: JavaScript で数値どうしの割り算をする
challengeType: 1
videoUrl: 'https://scrimba.com/c/cqkbdAr'
forumTopicId: 17566
dashedName: divide-one-number-by-another-with-javascript
---
# --description--
数値どうしの割り算をすることもできます。
JavaScript では除算記号として `/` を使用します。
**例**
```js
const 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
const quotient = 66 / 0;
```
# --solutions--
```js
const quotient = 66 / 33;
```

View File

@ -0,0 +1,99 @@
---
id: 56533eb9ac21ba0edf2244b6
title: 文字列内のエスケープシーケンス
challengeType: 1
videoUrl: 'https://scrimba.com/c/cvmqRh6'
forumTopicId: 17567
dashedName: escape-sequences-in-strings
---
# --description--
文字列の中で<dfn>エスケープ</dfn>できる文字は引用符だけではありません。 エスケープ文字を使用するのには 2 つ理由があります。
1. キャリッジリターンのように、他に入力する方法がない文字を使用できるようになります。
2. 文字列中で複数の引用符を表現でき、JavaScript が正しく解釈できるようになります。
前のチャレンジでは次のことを学習しました。
<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` に次の 3 行のテキストを代入してください。
<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
const myStr = ""; // Change this line
```
# --solutions--
```js
const myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
```

View File

@ -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
const 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--
2 つのダブルクォート (`"`) と 4 つのエスケープされたダブルクォート (`\"`) を使用する必要があります。
```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
const myStr = ""; // Change this line
```
# --solutions--
```js
const myStr = "I am a \"double quoted\" string inside \"double quotes\".";
```

View File

@ -0,0 +1,74 @@
---
id: 587d7b87367417b2b2512b3f
title: var キーワードと let キーワードの違いについて
challengeType: 1
forumTopicId: 301202
dashedName: explore-differences-between-the-var-and-let-keywords
---
# --description--
`var` キーワードによる変数宣言の最も大きな問題の一つは、簡単に変数宣言を上書きできてしまうことです。
```js
var camper = "James";
var camper = "David";
console.log(camper);
```
上記のコードで、変数 `camper` は最初は `James` として宣言されていますが、その後 `David` に上書きされています。 そのためコンソールには文字列 `David` が表示されます。
小規模なアプリケーションであれば、こうした問題は起きにくいかもしれまん。 しかし、コードの規模が大きくなると、変数を意図せずに誤って上書きしてしまう可能性が高くなります。 このような動作はエラーを返さないため、バグを見つけて修正することが難しくなります。
JavaScript の大きなアップデートとなった ES6 では、`var`キーワードに伴うこうした潜在的な問題を解決するために `let` というキーワードが導入されました。 以降のチャレンジでは ES6 の他の機能についても学習します。
上記のコードの `var``let` に置き換えた場合、結果はエラーになります。
```js
let camper = "James";
let camper = "David";
```
エラーはブラウザーコンソールで確認できます。
`var` とは違って、`let` を使用する場合は、同じ名前を持つ変数は一度だけしか宣言できません。
# --instructions--
`let` キーワードだけを使用するようにコードを更新してください。
# --hints--
`var` がコード内に存在しない必要があります。
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
`catName` は文字列 `Oliver` である必要があります。
```js
assert(catName === 'Oliver');
```
`catSound` は文字列 `Meow!` である必要があります。
```js
assert(catSound === 'Meow!');
```
# --seed--
## --seed-contents--
```js
var catName = "Oliver";
var catSound = "Meow!";
```
# --solutions--
```js
let catName = "Oliver";
let catSound = "Meow!";
```

View File

@ -0,0 +1,68 @@
---
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` がコンソールに表示されます。
たとえば、変数 `const firstName = "Ada"` を作成した場合、`firstName.length` プロパティを使用して文字列 `Ada` の長さを取得できます。
# --instructions--
`.length` プロパティを使用して、`lastName` 変数の文字数をカウントし、それを `lastNameLength` に代入してください。
# --hints--
`// Setup` セクションの変数宣言を変更しないでください。
```js
assert(
code.match(/let lastNameLength = 0;/) &&
code.match(/const lastName = "Lovelace";/)
);
```
`lastNameLength` は 8 になる必要があります。
```js
assert(typeof lastNameLength !== 'undefined' && lastNameLength === 8);
```
`lastName.length` のように、`.length` を使用して `lastName` の長さを取得する必要があります。
```js
assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
```
# --seed--
## --seed-contents--
```js
// Setup
let lastNameLength = 0;
const lastName = "Lovelace";
// Only change code below this line
lastNameLength = lastName;
```
# --solutions--
```js
let lastNameLength = 0;
const lastName = "Lovelace";
lastNameLength = lastName.length;
```

View File

@ -0,0 +1,67 @@
---
id: 56533eb9ac21ba0edf2244ae
title: JavaScript で割り算の余りを求める
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWP24Ub'
forumTopicId: 18184
dashedName: finding-a-remainder-in-javascript
---
# --description--
<dfn>剰余</dfn>演算子 `%` は 2 つの数値の割り算の余りを取得します。
**例**
<blockquote>5 % 2 = 1 なぜならば<br>Math.floor(5 / 2) = 2 (割り算の商)<br>2 * 2 = 4<br>5 - 4 = 1 (割り算の余り)</blockquote>
**使用例**
数学では、ある数が偶数か奇数かを求めるために、その数を `2` で割った余りを調べることができます。
<blockquote>17 % 2 = 1 (17 は奇数)<br>48 % 2 = 0 (48 は偶数)</blockquote>
**注:** <dfn>剰余</dfn>演算子はしばしばモジュロ演算子と混同されることがあります。 剰余はモジュロと非常によく似ていますが、負数では正しく機能しません。
# --instructions--
<dfn>剰余</dfn> (`%`) 演算子を使用して、`remainder``11``3` で割った余りと等しくなるように設定してください。
# --hints--
変数 `remainder` を初期化する必要があります。
```js
assert(/(const|let|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
const remainder = 0;
```
# --solutions--
```js
const remainder = 11 % 3;
```

View File

@ -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 には、`0` (含む) から `1` (含まない) の間の小数の乱数を生成する `Math.random()` 関数があります。 つまり、`Math.random()``0` を返すことはありますが、`1` を返すことは決してありません。
**注意:** [代入演算子による値の格納](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator)の場合と同様に、すべての関数呼び出しは `return` が実行される前に解決されるため、`Math.random()` 関数の値を `return` することができます。
# --instructions--
`0` の代わりに乱数を返すように、`randomFraction` を変更してください。
# --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();
}
```

View File

@ -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);
}
```

View File

@ -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--
前回は、ゼロから指定した数値までの整数の乱数を生成しましたが、2 つの特定の数値の範囲内で整数の乱数を生成することができます。
それには最小値 `min` と最大値 `max` を定義します。
ここでは次のような式を使用します。 このコードの動作を理解して確かめてみてください。
```js
Math.floor(Math.random() * (max - min + 1)) + min
```
# --instructions--
`myMin` から `myMax` までを範囲とする `randomRange` という関数を作成し、`myMin` 以上 `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;
}
```

View File

@ -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>のスコープを持ちます。 つまり、JavaScript コードのどこからでもその変数を参照することができます。
`let` キーワードまたは `const` キーワードを使用せずに宣言された変数は、自動的に `global` スコープで作成されます。 これは、コード内の他の場所で、または関数を再び実行するときに、意図しない結果を引き起こす可能性があります。 変数は常に `let` または `const` で宣言するようにしてください。
# --instructions--
`let` または `const`を使用して、関数の外部で `myGlobal` という名前のグローバル変数を宣言し、 値 `10` で初期化してください。
関数 `fun1` の内側で、`let` キーワードまたは `const` キーワードを***使用せずに***、`oopsGlobal``5` を代入してください。
# --hints--
`myGlobal` を定義する必要があります。
```js
assert(typeof myGlobal != 'undefined');
```
`myGlobal` の値は `10` である必要があります。
```js
assert(myGlobal === 10);
```
`myGlobal``let` キーワードまたは `const` キーワードを使用して宣言する必要があります。
```js
assert(/(let|const)\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
const 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);
}
```

View File

@ -0,0 +1,77 @@
---
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>変数で同じ名前を使用することが可能です。 その場合は、ローカル変数がグローバル変数よりも優先されます。
次の例を見てみましょう。
```js
const someVar = "Hat";
function myFun() {
const someVar = "Head";
return someVar;
}
```
ローカルの変数が存在するため、関数 `myFun` は文字列 `Head` を返します。
# --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
const outerWear = "T-Shirt";
function myOutfit() {
// Only change code below this line
// Only change code above this line
return outerWear;
}
myOutfit();
```
# --solutions--
```js
const outerWear = "T-Shirt";
function myOutfit() {
const outerWear = "sweater";
return outerWear;
}
```

View File

@ -0,0 +1,136 @@
---
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>&#x3C;= 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
const 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!";
}
```

View File

@ -0,0 +1,80 @@
---
id: 56533eb9ac21ba0edf2244ac
title: JavaScript で数値をインクリメントする
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8GLT9'
forumTopicId: 18201
dashedName: increment-a-number-with-javascript
---
# --description--
`++` 演算子を使用して簡単に変数の値を 1 増やす (<dfn>インクリメント</dfn>する) ことができます。
```js
i++;
```
は次の式と等価です。
```js
i = i + 1;
```
**注:** この行全体が `i++;` となり、等号が不要になります。
# --instructions--
コードを変更して `myVar``++` 演算子を使用してください。
# --hints--
`myVar``88` に等しくなる必要があります。
```js
assert(myVar === 88);
```
代入演算子は使用しないでください。
```js
assert(
/let\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(/let myVar = 87;/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(z){return 'myVar = ' + z;})(myVar);
```
## --seed-contents--
```js
let myVar = 87;
// Only change code below this line
myVar = myVar + 1;
```
# --solutions--
```js
let myVar = 87;
myVar++;
```

View File

@ -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--
変数 `a``var` で定義し、値 `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;
```

View File

@ -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--
処理を必要とする条件が複数ある場合は、`if` ステートメントと `else 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--
2 つ以上の `else` ステートメントを記述する必要があります。
```js
assert(code.match(/else/g).length > 1);
```
2 つ以上の `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";
}
}
```

View File

@ -0,0 +1,106 @@
---
id: 56533eb9ac21ba0edf2244da
title: else ステートメントを導入する
challengeType: 1
videoUrl: 'https://scrimba.com/c/cek4Efq'
forumTopicId: 18207
dashedName: introducing-else-statements
---
# --description--
`if` ステートメントの条件が true の場合は、その後のコードブロックが実行されます。 条件が false の場合はどうなるでしょうか? 通常は何も起こりません。 `else` ステートメントを記述することによって、 別のコードブロックを実行できます。
```js
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
```
# --instructions--
複数の `if` ステートメントを 1 つの `if/else` ステートメントにまとめてください。
# --hints--
エディターでは 1 つの `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(/let result = "";/.test(code) && /return result;/.test(code));
```
# --seed--
## --seed-contents--
```js
function testElse(val) {
let 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) {
let result = "";
if(val > 5) {
result = "Bigger than 5";
} else {
result = "5 or Smaller";
}
return result;
}
```

View File

@ -0,0 +1,69 @@
---
id: 56104e9e514f539506016a5c
title: for ループによる奇数の繰り返し処理
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm8n7T9'
forumTopicId: 18212
dashedName: iterate-odd-numbers-with-a-for-loop
---
# --description--
for ステートメントのループ処理は必ずしも 1 回に 1 つずつ繰り返す必要はありません。 `final-expression` の部分を変更して偶数ずつカウントすることができます。
`i = 0` から始めて、`i < 10` の間、ループ処理を行います。 `i += 2` で、`i` をループごとに 2 ずつインクリメントします。
```js
const ourArray = [];
for (let i = 0; i < 10; i += 2) {
ourArray.push(i);
}
```
`ourArray` には `[0, 2, 4, 6, 8]` が格納されます。 奇数をカウントできるように `initialization` の部分を変更してみましょう。
# --instructions--
`for` ループを使用して、1 から 9 までの奇数を `myArray` に push してください。
# --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
const myArray = [];
// Only change code below this line
```
# --solutions--
```js
const myArray = [];
for (let i = 1; i < 10; i += 2) {
myArray.push(i);
}
```

View File

@ -0,0 +1,81 @@
---
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
const arr = [10, 9, 8, 7, 6];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
配列は 0 から始まるインデックスを持つことに注意してください。つまり、配列の最後のインデックスは `length - 1` になります。 このループ処理の条件は `i < arr.length` となっていて、`i``length` に等しくなるとループ処理を終了します。 この例では、最後の繰り返しは `i === 4` です。つまり、`i``arr.length - 1` に等しくなり、コンソールに `6` を出力します。 その後、`i` が加算されて `5` になると、`i < arr.length``false` となるため、ループ処理は終了します。
# --instructions--
変数 `total` を宣言し、`0` に初期化してください。 `for` ループを使用して、`myArr` 配列の各要素の値を `total` に追加してください。
# --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));
```
値 20 を直接 `total` に代入しないでください。
```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
const myArr = [2, 3, 4, 5, 6];
// Only change code below this line
```
# --solutions--
```js
const myArr = [2, 3, 4, 5, 6];
let total = 0;
for (let i = 0; i < myArr.length; i++) {
total += myArr[i];
}
```

View File

@ -0,0 +1,105 @@
---
id: 5a2efd662fb457916e1fe604
title: JavaScript の do...while ループによる繰り返し処理
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDqWGcp'
forumTopicId: 301172
dashedName: iterate-with-javascript-do---while-loops
---
# --description--
次に学ぶループ処理のタイプは `do...while` ループと呼ばれるものです。 この処理が `do...while` ループと呼ばれるのは、最初にループ内のコードが無条件に 1 回実行 (`do`) され、その後、指定された条件が `true` と評価される間ずっと (`while`)、ループ処理が実行され続けるからです。
```js
const ourArray = [];
let i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
```
上記の例も他のタイプのループと同様の処理を行い、配列の結果は `[0, 1, 2, 3, 4]` のようになります。 しかし、`do...while` は他のループとは違って、最初の評価で条件を満たさない場合の動作が異なります。 これを実際の例で見ていきましょう。次は `i < 5` である限りループ処理を実行する通常の `while` ループです。
```js
const ourArray = [];
let i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
```
この例では、`ourArray` の値を空の配列に初期化し、`i` の値を 5 に初期化しています。 この `while` ループを実行すると、`i` が 5 未満ではないため、条件の評価が `false` となり、ループ内のコードは実行されません。 その結果、`ourArray` には何も値が追加されません。上記の例のコードの実行がすべて完了しても `[]` のままです。 次に、`do...while` ループを見てみましょう。
```js
const ourArray = [];
let i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);
```
この例でも、`while` ループの場合と同じように、`i` の値を 5 に初期化しています。 次の行に進むと、評価すべき条件がないため、中括弧内のコードに進み、そのコードを実行します。 そこでは配列に要素を 1つ追加し、`i` をインクリメントしてから、条件の評価に移ります。 最後の行で最終的に条件 `i < 5` を評価するときは、`i` は 6 になっていて、条件を満たさないため、ループを抜けて終了します。 上記の例の最後では、`ourArray` の値は `[5]` になっています。 `do...while` ループはその性質上、ループ内のコードを少なくとも 1 回は必ず実行します。 `do...while` ループを利用して配列に値を push してみましょう。
# --instructions--
コードの `while` ループを `do...while` ループに変更して、`myArray` に値 `10` だけを push し、コードの実行終了時に `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
const myArray = [];
let i = 10;
// Only change code below this line
while (i < 5) {
myArray.push(i);
i++;
}
```
# --solutions--
```js
const myArray = [];
let i = 10;
do {
myArray.push(i);
i++;
} while (i < 5)
```

View File

@ -0,0 +1,81 @@
---
id: cf1111c1c11feddfaeb5bdef
title: JavaScript の for ループによる繰り返し処理
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9yNVCe'
forumTopicId: 18219
dashedName: iterate-with-javascript-for-loops
---
# --description--
ループ処理によって、同じコードを何度も実行できます。
JavaScript のループで最も一般的なのは、特定の回数を実行する `for` ループと呼ばれるものです。
for ループは、セミコロンで区切られた 3 つの任意の式を使用して
`for (a; b; c)` のように宣言します。ここで `a` は初期化式、`b` は条件式、`c` は最終式です。
初期化式は、ループが開始される前に 1 回だけ実行されます。 通常はループ変数の定義と設定に使用します。
条件式は各ループ処理の最初に評価され、`true` である限り繰り返されます。 繰り返し処理の開始時に条件が `false` になると、ループの実行が停止します。 したがって、条件の最初の評価が false の場合はループは決して実行されません。
最終式は各ループ処理の最後、次の条件評価の前に実行されます。通常はループカウンターのインクリメントまたはデクリメントに使用します。
次の例では、`i = 0` で初期化し、条件 `i < 5` が true である間、繰り返し処理を実行します。 最終式の `i++` により、各ループ処理で `i``1` ずつインクリメントします。
```js
const ourArray = [];
for (let i = 0; i < 5; i++) {
ourArray.push(i);
}
```
`ourArray` の値は `[0, 1, 2, 3, 4]` となります。
# --instructions--
`for` ループを使用して、1 から 5 までの値を `myArray` に push してください。
# --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
const myArray = [];
// Only change code below this line
```
# --solutions--
```js
const myArray = [];
for (let i = 1; i < 6; i++) {
myArray.push(i);
}
```

View File

@ -0,0 +1,75 @@
---
id: cf1111c1c11feddfaeb1bdef
title: JavaScript の while ループによる繰り返し処理
challengeType: 1
videoUrl: 'https://scrimba.com/c/c8QbnCM'
forumTopicId: 18220
dashedName: iterate-with-javascript-while-loops
---
# --description--
ループ処理によって、同じコードを何度も実行できます。
まず最初に `while` ループと呼ばれるループ型を学習します。こう呼ばれるのは特定の条件が true である間 (while) は実行され、条件が true でなくなると終了するためです。
```js
const ourArray = [];
let i = 0;
while (i < 5) {
ourArray.push(i);
i++;
}
```
上記のコード例では、`while` ループは 5 回実行され、0 から 4 までの数字を `ourArray` に追加します。
while ループを利用して配列に値を push してみましょう。
# --instructions--
`while` ループを使用して、`myArray` に数字 5 0 を降順に追加してください。
# --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
const myArray = [];
// Only change code below this line
```
# --solutions--
```js
const myArray = [];
let i = 5;
while (i >= 0) {
myArray.push(i);
i--;
}
```

View File

@ -0,0 +1,86 @@
---
id: 56533eb9ac21ba0edf2244bf
title: ローカルスコープと関数
challengeType: 1
videoUrl: 'https://scrimba.com/c/cd62NhM'
forumTopicId: 18227
dashedName: local-scope-and-functions
---
# --description--
関数内で宣言された変数や、関数のパラメーターは、<dfn>ローカル</dfn>のスコープを持ちます。 つまり、それらは関数内でのみ参照されます。
次は、`loc` というローカル変数を持つ関数 `myTest` です。
```js
function myTest() {
const loc = "foo";
console.log(loc);
}
myTest();
console.log(loc);
```
`myTest()` 関数の呼び出しでは、コンソールに文字列 `foo` が表示されます。 `console.log(loc)` の行はエラーをスローします。これは、関数の外側では `loc` が定義されていないためです。
# --instructions--
エディターにある 2 つの `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
let myVar;
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
```

Some files were not shown because too many files have changed in this diff Show More