chore(i18n,curriculum): update translations (#44138)
This commit is contained in:
@ -17,7 +17,7 @@ dashedName: assignment-with-a-returned-value
|
||||
ourSum = sum(5, 12);
|
||||
```
|
||||
|
||||
將會調用函數 `sum`,函數返回值 `17`,然後將該值賦給變量 `ourSum`。
|
||||
將調用 `sum` 函數,該函數返回 `17` 的值並將其分配給 `ourSum` 變量。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -49,13 +49,14 @@ assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var processed = 0;
|
||||
let processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -25,7 +25,7 @@ dashedName: comparison-with-the-inequality-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
在 `if` 語句中,添加不相等運算符 `!=`,這樣函數在當 `val` 不等於 `99` 的時候,會返回 `Not Equal`。
|
||||
在 `if` 語句中添加不等運算符 `!=` 以便函數在 `val` 不等於 `99` 時返回字符串 `Not Equal`。
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -26,7 +26,7 @@ dashedName: comparison-with-the-strict-equality-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
在 `if` 語句中,添加嚴格相等運算符,這樣函數在當 `val` 嚴格等於 `7` 的時候,會返回 `Equal`。
|
||||
在 `if` 語句中使用嚴格相等運算符,這樣當 `val` 嚴格等於 `7` 時,函數將返回字符串 `Equal`。
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -22,7 +22,7 @@ dashedName: concatenating-strings-with-plus-operator
|
||||
例如:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. " + "I come second.";
|
||||
const ourStr = "I come first. " + "I come second.";
|
||||
```
|
||||
|
||||
字符串 `I come first. I come second.` 將顯示在控制檯中。
|
||||
@ -44,10 +44,10 @@ assert(myStr === 'This is the start. This is the end.');
|
||||
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
|
||||
```
|
||||
|
||||
應使用 `var` 關鍵字創建 `myStr`。
|
||||
`myStr` 應該使用 `const` 關鍵字創建。
|
||||
|
||||
```js
|
||||
assert(/var\s+myStr/.test(code));
|
||||
assert(/const\s+myStr/.test(code));
|
||||
```
|
||||
|
||||
應把結果賦值給 `myStr` 變量。
|
||||
@ -73,11 +73,11 @@ assert(/myStr\s*=/.test(code));
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
const myStr = ""; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "This is the start. " + "This is the end.";
|
||||
const myStr = "This is the start. " + "This is the end.";
|
||||
```
|
||||
|
@ -16,13 +16,14 @@ dashedName: count-backwards-with-a-for-loop
|
||||
設置 `i = 10`,並且當 `i > 0` 的時候才繼續循環。 我們使用 `i -= 2` 來讓 `i` 每次循環遞減 2。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 10; i > 0; i -= 2) {
|
||||
const ourArray = [];
|
||||
|
||||
for (let i = 10; i > 0; i -= 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
循環結束後,`ourArray` 的值爲 `[10,8,6,4,2]`。 讓我們改變初始值和最後的表達式,這樣我們就可以按照奇數從後往前兩兩倒着數。
|
||||
`ourArray` 現在將包含 `[10, 8, 6, 4, 2]`。 讓我們改變初始值和最後的表達式,這樣我們就可以按照奇數從後往前兩兩倒着數。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -60,16 +61,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 9; i > 0; i -= 2) {
|
||||
const myArray = [];
|
||||
for (let i = 9; i > 0; i -= 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b87367417b2b2512b41
|
||||
title: 用 const 關鍵字聲明只讀變量
|
||||
title: 使用 const 關鍵字聲明只讀變量
|
||||
challengeType: 1
|
||||
forumTopicId: 301201
|
||||
dashedName: declare-a-read-only-variable-with-the-const-keyword
|
||||
@ -8,50 +8,62 @@ dashedName: declare-a-read-only-variable-with-the-const-keyword
|
||||
|
||||
# --description--
|
||||
|
||||
`let` 並不是唯一的新的聲明變量的方式。 在 ES6 裏面,你還可以使用 `const` 關鍵字來聲明變量。
|
||||
關鍵字 `let` 並不是聲明變量的唯一新方法。 在 ES6 中,你還可以使用 `const` 關鍵字聲明變量。
|
||||
|
||||
`const` 擁有 `let` 的所有優點,不同的是,通過 `const` 聲明的變量是隻讀的。 這意味着通過 `const` 聲明的變量只能被賦值一次,而不能被再次賦值。
|
||||
`const` 具有 `let` 的所有出色功能,另外還有一個額外的好處,即使用 `const` 聲明的變量是隻讀的。 它們是一個常量值,這意味着一旦一個變量被賦值爲 `const`,它就不能被重新賦值:
|
||||
|
||||
```js
|
||||
const FAV_PET = "Cats";
|
||||
FAV_PET = "Dogs";
|
||||
```
|
||||
|
||||
控制檯將由於給 `FAV_PET` 重新賦值而顯示錯誤。
|
||||
由於重新分配 `FAV_PET` 的值,控制檯將顯示錯誤。
|
||||
|
||||
可見,嘗試給用 `const` 聲明的變量重新賦值會報錯。 你應該使用 `const` 關鍵字來聲明所有不打算再次賦值的變量。 這有助於避免給一個常量進行額外的再次賦值。 一個最佳實踐是對所有常量的命名採用全大寫字母,並在單詞之間使用下劃線進行分隔。
|
||||
你應該始終使用 `const` 關鍵字命名不想重新分配的變量。 這有助於避免給一個常量進行額外的再次賦值。
|
||||
|
||||
**注意:**通常,開發者會用大寫字母作爲常量標識符,用小寫字母或者駝峯命名作爲變量(對象或數組)標識符。 後面的挑戰會涉及到在數組中使用小寫變量標識符。
|
||||
命名常量的常見做法是全部使用大寫字母,單詞之間用下劃線分隔。
|
||||
|
||||
**注意:** 對於不可變值,開發人員通常使用大寫變量標識符,對可變值(對象和數組)使用小寫或駝峯式標識符。 你將在後面的挑戰中瞭解有關對象、數組以及不可變和可變值的更多信息。 同樣在後面的挑戰中,你將看到大寫、小寫或駝峯式變量標識符的示例。
|
||||
|
||||
# --instructions--
|
||||
|
||||
改變以下代碼,使得所有的變量都使用 `let` 或 `const` 關鍵詞來聲明。 當變量將會改變的時候使用 `let` 關鍵字,當變量要保持常量的時候使用 `const` 關鍵字。 同時,對使用 `const` 聲明的變量按照最佳實踐重命名,變量名中的字母應該都是大寫的。
|
||||
更改代碼,以便使用 `let` 或 `const` 聲明所有變量。 當你希望變量改變時使用 `let`,而當你希望變量保持不變時使用 `const`。 此外,重命名用 `const` 聲明的變量以符合常見做法,這意味着常量應該全部大寫。
|
||||
|
||||
# --hints--
|
||||
|
||||
代碼中不應有 `var`。
|
||||
`var` 不應存在於你的代碼中。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/var/g));
|
||||
```
|
||||
|
||||
`SENTENCE` 應該是使用 `const` 聲明的常量。
|
||||
你應該將 `fCC` 更改爲全部大寫。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(const SENTENCE)/g));
|
||||
(getUserInput) => {
|
||||
assert(getUserInput('index').match(/(FCC)/));
|
||||
assert(!getUserInput('index').match(/fCC/));
|
||||
}
|
||||
```
|
||||
|
||||
`i` 應該是使用 `let`聲明的。
|
||||
`FCC` 應該是一個用 `const` 聲明的常量變量。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(let i)/g));
|
||||
assert.equal(FCC, 'freeCodeCamp');
|
||||
assert.match(code, /const\s+FCC/);
|
||||
```
|
||||
|
||||
`console.log` 應該修改爲用於打印 `SENTENCE` 變量。
|
||||
`fact` 應該用 `let` 聲明。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(let fact)/g));
|
||||
```
|
||||
|
||||
`console.log` 應該更改爲打印 `FCC` 和 `fact` 變量。
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
assert(getUserInput('index').match(/console\.log\(\s*SENTENCE\s*\)\s*;?/g));
|
||||
assert(getUserInput('index').match(/console\.log\(\s*FCC\s*\,\s*fact\s*\)\s*;?/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -59,31 +71,18 @@ FAV_PET = "Dogs";
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function printManyTimes(str) {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var sentence = str + " is cool!";
|
||||
for (var i = 0; i < str.length; i+=2) {
|
||||
console.log(sentence);
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
}
|
||||
printManyTimes("freeCodeCamp");
|
||||
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
|
||||
function printManyTimes(str) {
|
||||
const FCC = "freeCodeCamp";
|
||||
let fact = "is cool!";
|
||||
|
||||
const SENTENCE = str + " is cool!";
|
||||
for (let i = 0; i < str.length; i+=2) {
|
||||
console.log(SENTENCE);
|
||||
}
|
||||
|
||||
}
|
||||
printManyTimes("freeCodeCamp");
|
||||
fact = "is awesome!";
|
||||
console.log(FCC, fact);
|
||||
```
|
||||
|
@ -9,21 +9,27 @@ dashedName: declare-string-variables
|
||||
|
||||
# --description--
|
||||
|
||||
之前我們寫過這樣的代碼:
|
||||
之前,你使用以下代碼聲明變量:
|
||||
|
||||
```js
|
||||
var myName;
|
||||
```
|
||||
|
||||
但是你也可以像這樣聲明一個字符串變量:
|
||||
|
||||
```js
|
||||
var myName = "your name";
|
||||
```
|
||||
|
||||
`"your name"` 被稱作<dfn>字符串</dfn><dfn>字面量</dfn>。 這是一個字符串,因爲它是一系列包含在單引號或雙引號中的零或多個字符。
|
||||
`"your name"` 被稱爲 <dfn>string</dfn> <dfn>literal</dfn>。 字符串文字或字符串是用單引號或雙引號括起來的一系列零個或多個字符。
|
||||
|
||||
# --instructions--
|
||||
|
||||
創建兩個新的字符串變量:`myFirstName` 和 `myLastName`,並用你的姓和名分別爲它們賦值。
|
||||
創建兩個新的字符串變量:`myFirstName` 和 `myLastName`,並分別爲它們分配你的名字和姓氏的值。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myFirstName` 應該是一個字符串,至少包含一個字符。
|
||||
`myFirstName` 應該是一個至少包含一個字符的字符串。
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -41,7 +47,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myLastName` 應該是一個字符串,至少包含一個字符。
|
||||
`myLastName` 應該是一個至少包含一個字符的字符串。
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -8,55 +8,53 @@ dashedName: explore-differences-between-the-var-and-let-keywords
|
||||
|
||||
# --description--
|
||||
|
||||
使用 `var` 關鍵字來聲明變量,會出現重複聲明導致變量被覆蓋卻不會報錯的問題。
|
||||
使用 `var` 關鍵字聲明變量的最大問題之一是你可以輕鬆覆蓋變量聲明:
|
||||
|
||||
```js
|
||||
var camper = 'James';
|
||||
var camper = 'David';
|
||||
var camper = "James";
|
||||
var camper = "David";
|
||||
console.log(camper);
|
||||
```
|
||||
|
||||
這裏控制檯將顯示字符串 `David`。
|
||||
在上面的代碼中,`camper` 變量最初聲明爲 `James`,然後被覆蓋爲 `David`。 然後控制檯顯示字符串 `David`。
|
||||
|
||||
在上面的代碼中,`camper` 變量的初始值爲 `James`,然後又被覆蓋成了 `David`。 在小型的應用中,你可能不會遇到這樣的問題。但是當你的代碼規模變得更加龐大的時候,就可能會在不經意間覆蓋了之前定義的變量。 因爲這樣的情況不會報錯,所以搜索和修復 bug 會變得非常困難。
|
||||
在 ES6 中引入了新的關鍵字 `let` 來解決 `var` 關鍵字帶來的潛在問題。 如果你在上面的代碼中使用 `let` 關鍵字來代替 `var` 關鍵字,結果會是一個報錯。
|
||||
在小型應用程序中,你可能不會遇到此類問題。 但是隨着你的代碼庫變大,你可能會意外地覆蓋一個你不打算覆蓋的變量。 由於此行爲不會引發錯誤,因此搜索和修復錯誤變得更加困難。
|
||||
|
||||
ES6 中引入了一個名爲 `let` 的關鍵字,這是對 JavaScript 的一次重大更新,以解決與 `var` 關鍵字有關的潛在問題。 你將在後面的挑戰中瞭解其他 ES6 特性。
|
||||
|
||||
如果將上面代碼中的 `var` 替換爲 `let` ,則會導致錯誤:
|
||||
|
||||
```js
|
||||
let camper = 'James';
|
||||
let camper = 'David';
|
||||
let camper = "James";
|
||||
let camper = "David";
|
||||
```
|
||||
|
||||
你可以在瀏覽器的控制檯裏看見這個錯誤。 與 `var` 不同的是,當使用 `let` 的時候,同一名字的變量只能被聲明一次。 請注意 `"use strict"`。 這代表着開啓了嚴格模式,用於檢測常見的代碼錯誤以及“不安全”的行爲, 例如:
|
||||
該錯誤可以在你的瀏覽器控制檯中看到。
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
x = 3.14;
|
||||
```
|
||||
|
||||
這將顯示一個錯誤 `x is not defined`。
|
||||
所以不像 `var`,當你使用 `let` 時,同名的變量只能聲明一次。
|
||||
|
||||
# --instructions--
|
||||
|
||||
請更新這段代碼,只使用 `let` 關鍵字。
|
||||
更新代碼,使其僅使用 `let` 關鍵字。
|
||||
|
||||
# --hints--
|
||||
|
||||
代碼中不應有 `var`
|
||||
`var` 不應存在於代碼中。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/var/g));
|
||||
```
|
||||
|
||||
`catName` 變量的值應該爲 `Oliver`
|
||||
`catName` 應該是字符串 `Oliver`。
|
||||
|
||||
```js
|
||||
assert(catName === 'Oliver');
|
||||
```
|
||||
|
||||
`quote` 變量的值應該爲 `Oliver says Meow!`
|
||||
`catSound` 應該是字符串 `Meow!`
|
||||
|
||||
```js
|
||||
assert(quote === 'Oliver says Meow!');
|
||||
assert(catSound === 'Meow!');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -64,28 +62,13 @@ assert(quote === 'Oliver says Meow!');
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var catName;
|
||||
var quote;
|
||||
function catTalk() {
|
||||
"use strict";
|
||||
|
||||
catName = "Oliver";
|
||||
quote = catName + " says Meow!";
|
||||
|
||||
}
|
||||
catTalk();
|
||||
var catName = "Oliver";
|
||||
var catSound = "Meow!";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let catName;
|
||||
let quote;
|
||||
function catTalk() {
|
||||
'use strict';
|
||||
|
||||
catName = 'Oliver';
|
||||
quote = catName + ' says Meow!';
|
||||
}
|
||||
catTalk();
|
||||
let catName = "Oliver";
|
||||
let catSound = "Meow!";
|
||||
```
|
||||
|
@ -17,7 +17,7 @@ console.log("Alan Peter".length);
|
||||
|
||||
字符串 `10` 將會出現在控制檯中。
|
||||
|
||||
例如,如果我們創建了一個變量 `var firstName = "Ada"`,我們就可以通過使用 `firstName.length` 屬性來獲得字符串 `Ada` 的長度。
|
||||
例如,如果我們創建了一個變量 `const firstName = "Ada"`,我們可以通過使用 `firstName.length` 找出字符串 `Ada` 的長度屬性。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -29,8 +29,8 @@ console.log("Alan Peter".length);
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/var lastNameLength = 0;/) &&
|
||||
code.match(/var lastName = "Lovelace";/)
|
||||
code.match(/let lastNameLength = 0;/) &&
|
||||
code.match(/const lastName = "Lovelace";/)
|
||||
);
|
||||
```
|
||||
|
||||
@ -52,18 +52,17 @@ assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
let lastNameLength = 0;
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
lastNameLength = lastName;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
let lastNameLength = 0;
|
||||
const lastName = "Lovelace";
|
||||
lastNameLength = lastName.length;
|
||||
```
|
||||
|
@ -11,13 +11,13 @@ dashedName: global-scope-and-functions
|
||||
|
||||
在 JavaScript 中,<dfn>作用域</dfn>涉及到變量的作用範圍。 在函數外定義的變量具有 <dfn>全局</dfn> 作用域。 這意味着,具有全局作用域的變量可以在代碼的任何地方被調用。
|
||||
|
||||
這些沒有使用 `var` 關鍵字定義的變量,會被自動創建在 `global` 作用域中,形成全局變量。 當在代碼其他地方無意間定義了一個變量,剛好變量名與全局變量相同,這時會產生意想不到的後果。 因此你應該總是使用 `var` 關鍵字來聲明你的變量。
|
||||
未使用 `let` 或 `const` 關鍵字聲明的變量會在 `global` 範圍內自動創建。 當在代碼其他地方無意間定義了一個變量,剛好變量名與全局變量相同,這時會產生意想不到的後果。 你應該總是用 `let` 或 `const` 聲明你的變量。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `var`,在函數外聲明一個全局變量 `myGlobal`, 並給它一個初始值 `10`。
|
||||
使用 `let` 或 `const`,在任何函數之外聲明一個名爲 `myGlobal` 的全局變量。 並給它一個初始值 `10`。
|
||||
|
||||
在函數 `fun1` 的內部,***不***使用 `var` 關鍵字,聲明 `oopsGlobal`,並給它賦值爲 `5`。
|
||||
在函數 `fun1` 中,***不要*** 使用 `let` 或 `const` 關鍵字,將 `5` 分配給 `oopsGlobal` 。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -33,10 +33,10 @@ assert(typeof myGlobal != 'undefined');
|
||||
assert(myGlobal === 10);
|
||||
```
|
||||
|
||||
應使用 `var` 關鍵字定義 `myGlobal`。
|
||||
`myGlobal` 應該使用 `let` 或 `const` 關鍵字聲明
|
||||
|
||||
```js
|
||||
assert(/var\s+myGlobal/.test(code));
|
||||
assert(/(let|const)\s+myGlobal/.test(code));
|
||||
```
|
||||
|
||||
`oopsGlobal` 應爲全局變量,值爲 `5`。
|
||||
@ -109,7 +109,7 @@ function fun2() {
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myGlobal = 10;
|
||||
const myGlobal = 10;
|
||||
|
||||
function fun1() {
|
||||
oopsGlobal = 5;
|
||||
|
@ -14,13 +14,14 @@ dashedName: iterate-odd-numbers-with-a-for-loop
|
||||
初始化 `i = 0`,當 `i < 10` 的時候繼續循環。 `i += 2` 讓 `i` 每次循環之後增加 2。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 10; i += 2) {
|
||||
const ourArray = [];
|
||||
|
||||
for (let i = 0; i < 10; i += 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
循環結束後,`ourArray` 的值爲 `[0,2,4,6,8]`。 改變計數器(`initialization`) ,這樣我們可以用奇數來遞增。
|
||||
`ourArray` 現在將包含 `[0, 2, 4, 6, 8]`。 改變計數器(`initialization`) ,這樣我們可以用奇數來遞增。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -34,7 +35,7 @@ for (var i = 0; i < 10; i += 2) {
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` 應該等於 `[1,3,5,7,9]`
|
||||
`myArray` 應該等於 `[1, 3, 5, 7, 9]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
||||
@ -52,16 +53,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 10; i += 2) {
|
||||
const myArray = [];
|
||||
for (let i = 1; i < 10; i += 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
@ -15,7 +15,7 @@ JavaScript 中最常見的循環就是 `for`,它可以循環指定次數。
|
||||
|
||||
for 循環中的可選三個表達式用分號隔開:
|
||||
|
||||
`for (a; b; c)`,其中 `a` 爲初始化語句,`b` 是循環條件語句,`c` 是終止循環條件表達式。
|
||||
`for (a; b; c)`,其中`a`爲初始化語句,`b`爲條件語句,`c` 是最終的表達式。
|
||||
|
||||
初始化語句只會在執行循環開始之前執行一次。 它通常用於定義和設置你的循環變量。
|
||||
|
||||
@ -26,13 +26,14 @@ for 循環中的可選三個表達式用分號隔開:
|
||||
在下面的例子中,先初始化 `i = 0`,條件 `i < 5` 爲 true 時,進入循環。 每次循環後 `i` 的值增加 `1`,然後執行終止循環條件表達式 `i++`。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 5; i++) {
|
||||
const ourArray = [];
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
最終 `ourArray` 的值爲 `[0,1,2,3,4]`.
|
||||
`ourArray` 現在的值爲 `[0, 1, 2, 3, 4]`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -64,16 +65,17 @@ if (typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 6; i++) {
|
||||
const myArray = [];
|
||||
for (let i = 1; i < 6; i++) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
@ -14,8 +14,9 @@ dashedName: iterate-with-javascript-while-loops
|
||||
我們將學習的第一種類型的循環稱爲 `while` 循環,當 while 指定的條件爲真,循環纔會執行,反之不執行。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 0;
|
||||
const ourArray = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < 5) {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
@ -56,16 +57,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 5;
|
||||
const myArray = [];
|
||||
let i = 5;
|
||||
while (i >= 0) {
|
||||
myArray.push(i);
|
||||
i--;
|
||||
|
@ -16,8 +16,8 @@ dashedName: manipulate-arrays-with-pop
|
||||
數組中任何類型的元素(數值,字符串,甚至是數組)都可以被彈出來 。
|
||||
|
||||
```js
|
||||
var threeArr = [1, 4, 6];
|
||||
var oneDown = threeArr.pop();
|
||||
const threeArr = [1, 4, 6];
|
||||
const oneDown = threeArr.pop();
|
||||
console.log(oneDown);
|
||||
console.log(threeArr);
|
||||
```
|
||||
@ -26,7 +26,7 @@ console.log(threeArr);
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `.pop()` 函數移除 `myArray` 中的最後一個元素,並且把彈出的值賦給 `removedFromMyArray`。
|
||||
使用 `.pop()` 函數從 `myArray` 中刪除最後一項,並將取出的值分配給新變量 `removedFromMyArray`。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -69,22 +69,22 @@ assert(
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
if (typeof removedFromMyArray !== 'undefined') (function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
const myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
var removedFromMyArray = myArray.pop();
|
||||
const myArray = [["John", 23], ["cat", 2]];
|
||||
const removedFromMyArray = myArray.pop();
|
||||
```
|
||||
|
@ -16,15 +16,15 @@ dashedName: manipulate-arrays-with-shift
|
||||
示例:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", ["cat"]];
|
||||
var removedFromOurArray = ourArray.shift();
|
||||
const ourArray = ["Stimpson", "J", ["cat"]];
|
||||
const removedFromOurArray = ourArray.shift();
|
||||
```
|
||||
|
||||
`removedFromOurArray` 值爲 `Stimpson`,`ourArray` 值爲 `["J", ["cat"]]`
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `.shift()` 函數移除 `myArray` 中的第一項,並把移出的值賦給 `removedFromMyArray`。
|
||||
使用 `.shift()` 函數從 `myArray` 中刪除第一項,並將“移除的值”值分配給新變量 `removedFromMyArray`。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -65,24 +65,24 @@ assert(
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
if (typeof removedFromMyArray !== 'undefined') (function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray = myArray.shift();
|
||||
const removedFromMyArray = myArray.shift();
|
||||
```
|
||||
|
@ -16,7 +16,7 @@ dashedName: manipulate-arrays-with-unshift
|
||||
示例:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", "cat"];
|
||||
const ourArray = ["Stimpson", "J", "cat"];
|
||||
ourArray.shift();
|
||||
ourArray.unshift("Happy");
|
||||
```
|
||||
@ -25,7 +25,7 @@ ourArray.unshift("Happy");
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `unshift()` 函數把 `["Paul",35]` 加入到 `myArray` 的頭部。
|
||||
使用 `unshift()` 將 `["Paul", 35]` 添加到 `myArray` 變量的開頭。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -63,16 +63,17 @@ assert(
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
myArray.unshift(["Paul", 35]);
|
||||
```
|
||||
|
@ -9,12 +9,12 @@ dashedName: modify-array-data-with-indexes
|
||||
|
||||
# --description--
|
||||
|
||||
與字符串的數據不可變不同,數組的數據是可變的( <dfn>mutable</dfn>),可以自由地改變。
|
||||
與字符串不同,數組的條目是 <dfn>可變的</dfn> 並且可以自由更改,即使數組是用 `const` 聲明的。
|
||||
|
||||
**示例**
|
||||
|
||||
```js
|
||||
var ourArray = [50,40,30];
|
||||
const ourArray = [50, 40, 30];
|
||||
ourArray[0] = 15;
|
||||
```
|
||||
|
||||
@ -28,7 +28,7 @@ ourArray[0] = 15;
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` 應該等於 `[45,64,99]`。
|
||||
`myArray` 現在應該是 `[45, 64, 99]`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -73,14 +73,15 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [18,64,99];
|
||||
const myArray = [18, 64, 99];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [18,64,99];
|
||||
const myArray = [18, 64, 99];
|
||||
myArray[0] = 45;
|
||||
```
|
||||
|
@ -12,11 +12,12 @@ dashedName: nesting-for-loops
|
||||
如果你有一個二維數組,可以使用相同的邏輯,先遍歷外面的數組,再遍歷裏面的子數組。 下面是一個例子:
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
const arr = [
|
||||
[1, 2], [3, 4], [5, 6]
|
||||
];
|
||||
for (var i=0; i < arr.length; i++) {
|
||||
for (var j=0; j < arr[i].length; j++) {
|
||||
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
for (let j = 0; j < arr[i].length; j++) {
|
||||
console.log(arr[i][j]);
|
||||
}
|
||||
}
|
||||
@ -66,7 +67,7 @@ assert(
|
||||
|
||||
```js
|
||||
function multiplyAll(arr) {
|
||||
var product = 1;
|
||||
let product = 1;
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
@ -80,14 +81,12 @@ multiplyAll([[1,2],[3,4],[5,6,7]]);
|
||||
|
||||
```js
|
||||
function multiplyAll(arr) {
|
||||
var product = 1;
|
||||
for (var i = 0; i < arr.length; i++) {
|
||||
for (var j = 0; j < arr[i].length; j++) {
|
||||
let product = 1;
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
for (let j = 0; j < arr[i].length; j++) {
|
||||
product *= arr[i][j];
|
||||
}
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
multiplyAll([[1,2],[3,4],[5,6,7]]);
|
||||
```
|
||||
|
@ -13,13 +13,13 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
|
||||
|
||||
大多數現代編程語言,如 JavaScript,不同於人類從 1 開始計數。 它們是從 0 開始計數。 這被稱爲基於零(<dfn>Zero-based</dfn>)的索引。
|
||||
|
||||
例如,單詞 `Charles` 的索引 0 的字符是 `C`。 所以在 `var firstName = "Charles"` 中,你可以使用 `firstName[0]` 來獲得第一個位置上的字符。
|
||||
例如,單詞 `Charles` 的索引 0 的字符是 `C`。 所以如果 `const firstName = "Charles"`,你可以通過 `firstName[0]` 得到字符串第一個字母的值。
|
||||
|
||||
示例:
|
||||
|
||||
```js
|
||||
var firstName = "Charles";
|
||||
var firstLetter = firstName[0];
|
||||
const firstName = "Charles";
|
||||
const firstLetter = firstName[0];
|
||||
```
|
||||
|
||||
`firstLetter` 值爲字符串 `C` 。
|
||||
@ -56,8 +56,8 @@ assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
let firstLetterOfLastName = "";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName; // Change this line
|
||||
@ -66,8 +66,8 @@ firstLetterOfLastName = lastName; // Change this line
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
let firstLetterOfLastName = "";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName[0];
|
||||
|
@ -11,13 +11,13 @@ dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
|
||||
|
||||
要獲取字符串的最後一個字符,可以用字符串的長度減 1 的索引值。
|
||||
|
||||
例如,如果 `var firstName = "Ada"` 中,那麼你可以通過 `firstName[firstName.length - 1]` 來得到字符串的最後的一個字符。
|
||||
例如,如果 `const firstName = "Ada"`,則可以使用 `firstName[firstName.length - 1]` 獲取字符串最後一個字母的值。
|
||||
|
||||
示例:
|
||||
|
||||
```js
|
||||
var firstName = "Ada";
|
||||
var lastLetter = firstName[firstName.length - 1];
|
||||
const firstName = "Ada";
|
||||
const lastLetter = firstName[firstName.length - 1];
|
||||
```
|
||||
|
||||
`lastLetter` 值爲字符串 `a`。
|
||||
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var lastLetterOfLastName = lastName; // Change this line
|
||||
const lastLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var lastLetterOfLastName = lastName[lastName.length - 1];
|
||||
const lastName = "Lovelace";
|
||||
const lastLetterOfLastName = lastName[lastName.length - 1];
|
||||
```
|
||||
|
@ -11,13 +11,13 @@ dashedName: use-bracket-notation-to-find-the-nth-to-last-character-in-a-string
|
||||
|
||||
我們既可以獲取字符串的最後一個字符,也可以用獲取字符串的倒數第 N 個字符。
|
||||
|
||||
例如,你可以通過 `firstName[firstName.length - 3]` 來獲得 `var firstName = "Augusta"` 字符串中的倒數第三個字符。
|
||||
例如,你可以使用 `firstName[firstName.length - 3]` 獲取 `const firstName = "Augusta"` 字符串的倒數第三個字母的值
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
var firstName = "Augusta";
|
||||
var thirdToLastLetter = firstName[firstName.length - 3];
|
||||
const firstName = "Augusta";
|
||||
const thirdToLastLetter = firstName[firstName.length - 3];
|
||||
```
|
||||
|
||||
`thirdToLastLetter` 的值應該爲字符串 `s`。
|
||||
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var secondToLastLetterOfLastName = lastName; // Change this line
|
||||
const secondToLastLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var secondToLastLetterOfLastName = lastName[lastName.length - 2];
|
||||
const lastName = "Lovelace";
|
||||
const secondToLastLetterOfLastName = lastName[lastName.length - 2];
|
||||
```
|
||||
|
@ -9,7 +9,7 @@ dashedName: use-conditional-logic-with-if-statements
|
||||
|
||||
# --description--
|
||||
|
||||
`If` 語句用於在代碼中做條件判斷。 關鍵字 `if` 告訴 JavaScript 在小括號中的條件爲真的情況下去執行定義在大括號裏面的代碼。 這種條件被稱爲 `Boolean` 條件,因爲他們只可能是 `true`(真)或 `false`(假)。
|
||||
`if` 語句用於在代碼中做出決定。 關鍵字 `if` 告訴 JavaScript 在小括號中的條件爲真的情況下去執行定義在大括號裏面的代碼。 這種條件被稱爲 `Boolean` 條件,因爲他們只可能是 `true`(真)或 `false`(假)。
|
||||
|
||||
當條件的計算結果爲 `true`,程序執行大括號內的語句。 當布爾條件的計算結果爲 `false`,大括號內的代碼將不會執行。
|
||||
|
||||
@ -26,6 +26,7 @@ function test (myCondition) {
|
||||
}
|
||||
return "It was false";
|
||||
}
|
||||
|
||||
test(true);
|
||||
test(false);
|
||||
```
|
||||
|
@ -8,11 +8,13 @@ dashedName: compare-scopes-of-the-var-and-let-keywords
|
||||
|
||||
# --description--
|
||||
|
||||
使用 `var` 關鍵字來聲明一個變量的時候,這個變量會被聲明成全局變量,或是函數內的局部變量。
|
||||
如果你不熟悉 `let`,請查看 [這個挑戰](/learn/javascript-algorithms-and-data-structures/basic-javascript/explore-differences-between-the-var-and-let-keywords)。
|
||||
|
||||
`let` 關鍵字的作用與此類似,但會有一些額外的特性。 如果在代碼塊、語句或表達式中使用關鍵字 `let` 聲明變量,這個變量的作用域就被限制在當前的代碼塊、語句或表達式之中。
|
||||
使用 `var` 關鍵字聲明變量時,它是全局聲明的,如果在函數內部聲明則是局部聲明的。
|
||||
|
||||
舉個例子:
|
||||
`let` 關鍵字的行爲類似,但有一些額外的功能。 在代碼塊、語句或表達式中使用 `let` 關鍵字聲明變量時,其作用域僅限於該代碼塊、語句或表達式。
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
var numArray = [];
|
||||
@ -23,9 +25,9 @@ console.log(numArray);
|
||||
console.log(i);
|
||||
```
|
||||
|
||||
這裏控制檯將顯示值 `[0, 1, 2]` 和 `3`。
|
||||
此處控制檯將顯示值 `[0, 1, 2]` 和 `3`。
|
||||
|
||||
因爲使用了 `var` 關鍵字,`i` 被聲明爲全局變量。 所以當 `i++` 執行時,它會更新全局變量。 這個代碼和下方的代碼類似:
|
||||
使用 `var` 關鍵字,`i` 是全局聲明的。 所以當 `i++` 被執行時,它會更新全局變量。 此代碼類似於以下內容:
|
||||
|
||||
```js
|
||||
var numArray = [];
|
||||
@ -37,9 +39,9 @@ console.log(numArray);
|
||||
console.log(i);
|
||||
```
|
||||
|
||||
這裏控制檯將顯示值 `[0, 1, 2]` 和 `3`。
|
||||
此處控制檯將顯示值 `[0, 1, 2]` 和 `3`。
|
||||
|
||||
如果你創建一個函數,將它存儲起來,稍後在使用 `i` 變量的 `for` 循環中使用。這麼做可能會出現問題。 這是因爲存儲的函數會總是指向更新後的全局 `i` 變量的值。
|
||||
如果你創建一個函數,將它存儲起來,稍後在使用 `i` 變量的 `for` 循環中使用。這麼做可能會出現問題。 這是因爲存儲的函數將始終引用更新後的全局 `i` 變量的值。
|
||||
|
||||
```js
|
||||
var printNumTwo;
|
||||
@ -53,9 +55,9 @@ for (var i = 0; i < 3; i++) {
|
||||
console.log(printNumTwo());
|
||||
```
|
||||
|
||||
這裏控制檯將顯示值 `3`。
|
||||
此處控制檯將顯示值 `3`。
|
||||
|
||||
可以看到,`printNumTwo()` 打印了 3,而不是 2。 這是因爲賦值給 `i` 的值已經更新,`printNumTwo()` 返回全局的 `i`,而不是在 for 循環中創建函數時 `i` 的值。 `let` 關鍵字就不會出現這種現象:
|
||||
可以看到,`printNumTwo()` 打印了 3 而不是 2。 這是因爲賦值給 `i` 的值已經更新,`printNumTwo()` 返回全局的 `i`,而不是在 for 循環中創建函數時 `i` 的值。 `let` 關鍵字就不會出現這種現象:
|
||||
|
||||
```js
|
||||
let printNumTwo;
|
||||
@ -72,7 +74,7 @@ console.log(i);
|
||||
|
||||
在這裏控制檯將顯示值 `2` 和一個錯誤提示 `i is not defined`。
|
||||
|
||||
`i` 未定義,因爲它沒有在全局範圍內聲明。 它只在 `for` 循環語句中被聲明。 `printNumTwo()` 返回了正確的值,因爲 `let` 關鍵字在循環語句中使 `i` 變量產生了三個不同的值(分別爲 0、1、2)。
|
||||
`i` 未定義,因爲它沒有在全局範圍內聲明。 它只在 `for` 循環語句中被聲明。 `printNumTwo()` 返回了正確的值,因爲 `let` 關鍵字創建了三個具有唯一值(0、1 和 2)的不同 `i` 變量在循環語句中。
|
||||
|
||||
# --instructions--
|
||||
|
||||
|
@ -8,11 +8,13 @@ dashedName: mutate-an-array-declared-with-const
|
||||
|
||||
# --description--
|
||||
|
||||
在現代的 JavaScript 裏,`const` 聲明有很多用法。
|
||||
如果你不熟悉 `const`,請查看[這個挑戰](/learn/javascript-algorithms-and-data-structures/basic-javascript/declare-a-read-only-variable-with-the-const-keyword)。
|
||||
|
||||
一些開發者傾向於默認使用 `const` 來聲明所有變量,除非他們打算後續重新給變量賦值, 那麼他們在聲明的時候就會用 `let`。
|
||||
`const` 聲明在現代 JavaScript 中有很多用例。
|
||||
|
||||
然而,你要注意,對象(包括數組和函數)在使用 `const` 聲明的時候依然是可變的。 使用 `const` 來聲明只會保證變量不會被重新賦值。
|
||||
默認情況下,一些開發人員更喜歡使用 `const` 分配所有變量,除非他們知道需要重新分配值。 只有在這種情況下,他們才使用 `let`。
|
||||
|
||||
但是,重要的是要了解使用 `const` 分配給變量的對象(包括數組和函數)仍然是可變的。 使用 `const` 聲明只能防止變量標識符的重新分配。
|
||||
|
||||
```js
|
||||
const s = [5, 6, 7];
|
||||
@ -21,13 +23,13 @@ s[2] = 45;
|
||||
console.log(s);
|
||||
```
|
||||
|
||||
`s = [1, 2, 3]` 會導致一個錯誤。 `console.log` 會顯示值 `[5, 6, 45]`。
|
||||
`s = [1, 2, 3]` 將導致錯誤。 `console.log` 將顯示值 `[5, 6, 45]`。
|
||||
|
||||
可以發現,你可以改變對象 `[5, 6, 7]` 本身,而變量 `s` 會指向改變後的數組 `[5, 6, 45]`。 和所有數組一樣,數組 `s` 中的元素是可以被改變的,但是因爲使用了 `const` 關鍵字,你不能使用賦值操作符將變量標識 `s` 指向另外一個數組。
|
||||
如你所見,你可以改變對象 `[5, 6, 7]` 本身,變量 `s` 仍將指向更改後的數組 `[5, 6, 45]`。 像所有數組一樣,`s` 中的數組元素是可變的,但是因爲使用了 `const`,所以不能使用變量標識符 `s` 來指向一個使用賦值運算符的不同數組。
|
||||
|
||||
# --instructions--
|
||||
|
||||
這裏有一個使用 `const s = [5, 7, 2]` 聲明的數組。 使用對各元素賦值的方法將數組改成 `[2, 5, 7]`。
|
||||
數組聲明爲 `const s = [5, 7, 2]`。 使用對各元素賦值的方法將數組改成 `[2, 5, 7]`。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -37,7 +39,7 @@ console.log(s);
|
||||
(getUserInput) => assert(getUserInput('index').match(/const/g));
|
||||
```
|
||||
|
||||
`s` 應該爲常量(使用 `const`)。
|
||||
`s` 應該是一個常量變量(通過使用 `const`)。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/const\s+s/g));
|
||||
|
@ -10,7 +10,7 @@ dashedName: refactor-global-variables-out-of-functions
|
||||
|
||||
目前爲止,我們已經看到了函數式編程的兩個原則:
|
||||
|
||||
1) 不要更改變量或對象 - 創建新變量和對象,並在需要時從函數返回它們。 提示:使用類似 `var newArr = arrVar` 時 `arrVar` 是一個數組,代碼只是創建一個對現有變量的引用,而不是副本。 所以更改 `newArr` 中的值會同時更改 `arrVar` 中的值。
|
||||
1) 不要更改變量或對象 - 創建新變量和對象,並在需要時從函數返回它們。 提示:使用類似 `const newArr = arrVar` 的東西,其中 `arrVar` 是一個數組,只會創建對現有變量的引用,而不是副本。 所以更改 `newArr` 中的值會同時更改 `arrVar` 中的值。
|
||||
|
||||
2) 聲明函數參數 - 函數內的任何計算僅取決於參數,而不取決於任何全局對象或變量。
|
||||
|
||||
@ -86,7 +86,7 @@ assert(
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
// Change code below this line
|
||||
function add (bookName) {
|
||||
@ -99,7 +99,7 @@ function add (bookName) {
|
||||
|
||||
// Change code below this line
|
||||
function remove (bookName) {
|
||||
var book_index = bookList.indexOf(bookName);
|
||||
const book_index = bookList.indexOf(bookName);
|
||||
if (book_index >= 0) {
|
||||
|
||||
bookList.splice(book_index, 1);
|
||||
@ -109,9 +109,9 @@ function remove (bookName) {
|
||||
}
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
const newBookList = add(bookList, 'A Brief History of Time');
|
||||
const newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
const newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
|
||||
console.log(bookList);
|
||||
```
|
||||
@ -120,7 +120,7 @@ console.log(bookList);
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
function add(bookList, bookName) {
|
||||
return [...bookList, bookName];
|
||||
@ -135,7 +135,7 @@ function remove (bookList, bookName) {
|
||||
return bookListCopy;
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
const newBookList = add(bookList, 'A Brief History of Time');
|
||||
const newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
const newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
```
|
||||
|
@ -55,7 +55,7 @@ assert(code.match(/\s*\.\s*filter/g));
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
|
||||
```
|
||||
|
||||
`filteredList` 應等於 `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`。
|
||||
`filteredList` 應該等於 `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"}, {"title": "Batman Begins", "rating": "8.3"}]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(filteredList, [
|
||||
@ -72,7 +72,7 @@ assert.deepEqual(filteredList, [
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -187,7 +187,7 @@ var watchList = [
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var filteredList;
|
||||
const filteredList = "";
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
@ -197,8 +197,7 @@ console.log(filteredList);
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -311,7 +310,5 @@ var watchList = [
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
let filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
|
||||
// Only change code above this line
|
||||
const filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
|
||||
```
|
||||
|
@ -61,7 +61,7 @@ assert(!code.match(/for\s*?\([\s\S]*?\)/));
|
||||
assert(code.match(/\.map/g));
|
||||
```
|
||||
|
||||
`ratings` 應等於 `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`。
|
||||
`ratings` 應該等於 `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"},{"title": "Batman Begins", "rating": "8.3"}, {"title": "Avatar", "rating": "7.9"}]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(ratings, [
|
||||
@ -79,7 +79,7 @@ assert.deepEqual(ratings, [
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -194,8 +194,8 @@ var watchList = [
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var ratings = [];
|
||||
for(var i=0; i < watchList.length; i++){
|
||||
const ratings = [];
|
||||
for (let i = 0; i < watchList.length; i++) {
|
||||
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
|
||||
}
|
||||
|
||||
@ -207,8 +207,7 @@ console.log(JSON.stringify(ratings));
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -321,7 +320,7 @@ var watchList = [
|
||||
}
|
||||
];
|
||||
|
||||
var ratings = watchList.map(function(movie) {
|
||||
const ratings = watchList.map(function(movie) {
|
||||
return {
|
||||
title: movie["Title"],
|
||||
rating: movie["imdbRating"]
|
||||
|
@ -17,7 +17,7 @@ dashedName: assignment-with-a-returned-value
|
||||
ourSum = sum(5, 12);
|
||||
```
|
||||
|
||||
将会调用函数 `sum`,函数返回值 `17`,然后将该值赋给变量 `ourSum`。
|
||||
将调用 `sum` 函数,该函数返回 `17` 的值并将其分配给 `ourSum` 变量。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -49,13 +49,14 @@ assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var processed = 0;
|
||||
let processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -25,7 +25,7 @@ dashedName: comparison-with-the-inequality-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
在 `if` 语句中,添加不相等运算符 `!=`,这样函数在当 `val` 不等于 `99` 的时候,会返回 `Not Equal`。
|
||||
在 `if` 语句中添加不等运算符 `!=` 以便函数在 `val` 不等于 `99` 时返回字符串 `Not Equal`。
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -26,7 +26,7 @@ dashedName: comparison-with-the-strict-equality-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
在 `if` 语句中,添加严格相等运算符,这样函数在当 `val` 严格等于 `7` 的时候,会返回 `Equal`。
|
||||
在 `if` 语句中使用严格相等运算符,这样当 `val` 严格等于 `7` 时,函数将返回字符串 `Equal`。
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -22,7 +22,7 @@ dashedName: concatenating-strings-with-plus-operator
|
||||
例如:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. " + "I come second.";
|
||||
const ourStr = "I come first. " + "I come second.";
|
||||
```
|
||||
|
||||
字符串 `I come first. I come second.` 将显示在控制台中。
|
||||
@ -44,10 +44,10 @@ assert(myStr === 'This is the start. This is the end.');
|
||||
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
|
||||
```
|
||||
|
||||
应使用 `var` 关键字创建 `myStr`。
|
||||
`myStr` 应该使用 `const` 关键字创建。
|
||||
|
||||
```js
|
||||
assert(/var\s+myStr/.test(code));
|
||||
assert(/const\s+myStr/.test(code));
|
||||
```
|
||||
|
||||
应把结果赋值给 `myStr` 变量。
|
||||
@ -73,11 +73,11 @@ assert(/myStr\s*=/.test(code));
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
const myStr = ""; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "This is the start. " + "This is the end.";
|
||||
const myStr = "This is the start. " + "This is the end.";
|
||||
```
|
||||
|
@ -16,13 +16,14 @@ dashedName: count-backwards-with-a-for-loop
|
||||
设置 `i = 10`,并且当 `i > 0` 的时候才继续循环。 我们使用 `i -= 2` 来让 `i` 每次循环递减 2。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 10; i > 0; i -= 2) {
|
||||
const ourArray = [];
|
||||
|
||||
for (let i = 10; i > 0; i -= 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
循环结束后,`ourArray` 的值为 `[10,8,6,4,2]`。 让我们改变初始值和最后的表达式,这样我们就可以按照奇数从后往前两两倒着数。
|
||||
`ourArray` 现在将包含 `[10, 8, 6, 4, 2]`。 让我们改变初始值和最后的表达式,这样我们就可以按照奇数从后往前两两倒着数。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -60,16 +61,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 9; i > 0; i -= 2) {
|
||||
const myArray = [];
|
||||
for (let i = 9; i > 0; i -= 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b87367417b2b2512b41
|
||||
title: 用 const 关键字声明只读变量
|
||||
title: 使用 const 关键字声明只读变量
|
||||
challengeType: 1
|
||||
forumTopicId: 301201
|
||||
dashedName: declare-a-read-only-variable-with-the-const-keyword
|
||||
@ -8,50 +8,62 @@ dashedName: declare-a-read-only-variable-with-the-const-keyword
|
||||
|
||||
# --description--
|
||||
|
||||
`let` 并不是唯一的新的声明变量的方式。 在 ES6 里面,你还可以使用 `const` 关键字来声明变量。
|
||||
关键字 `let` 并不是声明变量的唯一新方法。 在 ES6 中,你还可以使用 `const` 关键字声明变量。
|
||||
|
||||
`const` 拥有 `let` 的所有优点,不同的是,通过 `const` 声明的变量是只读的。 这意味着通过 `const` 声明的变量只能被赋值一次,而不能被再次赋值。
|
||||
`const` 具有 `let` 的所有出色功能,另外还有一个额外的好处,即使用 `const` 声明的变量是只读的。 它们是一个常量值,这意味着一旦一个变量被赋值为 `const`,它就不能被重新赋值:
|
||||
|
||||
```js
|
||||
const FAV_PET = "Cats";
|
||||
FAV_PET = "Dogs";
|
||||
```
|
||||
|
||||
控制台将由于给 `FAV_PET` 重新赋值而显示错误。
|
||||
由于重新分配 `FAV_PET` 的值,控制台将显示错误。
|
||||
|
||||
可见,尝试给用 `const` 声明的变量重新赋值会报错。 你应该使用 `const` 关键字来声明所有不打算再次赋值的变量。 这有助于避免给一个常量进行额外的再次赋值。 一个最佳实践是对所有常量的命名采用全大写字母,并在单词之间使用下划线进行分隔。
|
||||
你应该始终使用 `const` 关键字命名不想重新分配的变量。 这有助于避免给一个常量进行额外的再次赋值。
|
||||
|
||||
**注意:**通常,开发者会用大写字母作为常量标识符,用小写字母或者驼峰命名作为变量(对象或数组)标识符。 后面的挑战会涉及到在数组中使用小写变量标识符。
|
||||
命名常量的常见做法是全部使用大写字母,单词之间用下划线分隔。
|
||||
|
||||
**注意:** 对于不可变值,开发人员通常使用大写变量标识符,对可变值(对象和数组)使用小写或驼峰式标识符。 你将在后面的挑战中了解有关对象、数组以及不可变和可变值的更多信息。 同样在后面的挑战中,你将看到大写、小写或驼峰式变量标识符的示例。
|
||||
|
||||
# --instructions--
|
||||
|
||||
改变以下代码,使得所有的变量都使用 `let` 或 `const` 关键词来声明。 当变量将会改变的时候使用 `let` 关键字,当变量要保持常量的时候使用 `const` 关键字。 同时,对使用 `const` 声明的变量按照最佳实践重命名,变量名中的字母应该都是大写的。
|
||||
更改代码,以便使用 `let` 或 `const` 声明所有变量。 当你希望变量改变时使用 `let`,而当你希望变量保持不变时使用 `const`。 此外,重命名用 `const` 声明的变量以符合常见做法,这意味着常量应该全部大写。
|
||||
|
||||
# --hints--
|
||||
|
||||
代码中不应有 `var`。
|
||||
`var` 不应存在于你的代码中。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/var/g));
|
||||
```
|
||||
|
||||
`SENTENCE` 应该是使用 `const` 声明的常量。
|
||||
你应该将 `fCC` 更改为全部大写。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(const SENTENCE)/g));
|
||||
(getUserInput) => {
|
||||
assert(getUserInput('index').match(/(FCC)/));
|
||||
assert(!getUserInput('index').match(/fCC/));
|
||||
}
|
||||
```
|
||||
|
||||
`i` 应该是使用 `let`声明的。
|
||||
`FCC` 应该是一个用 `const` 声明的常量变量。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(let i)/g));
|
||||
assert.equal(FCC, 'freeCodeCamp');
|
||||
assert.match(code, /const\s+FCC/);
|
||||
```
|
||||
|
||||
`console.log` 应该修改为用于打印 `SENTENCE` 变量。
|
||||
`fact` 应该用 `let` 声明。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(let fact)/g));
|
||||
```
|
||||
|
||||
`console.log` 应该更改为打印 `FCC` 和 `fact` 变量。
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
assert(getUserInput('index').match(/console\.log\(\s*SENTENCE\s*\)\s*;?/g));
|
||||
assert(getUserInput('index').match(/console\.log\(\s*FCC\s*\,\s*fact\s*\)\s*;?/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -59,31 +71,18 @@ FAV_PET = "Dogs";
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function printManyTimes(str) {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var sentence = str + " is cool!";
|
||||
for (var i = 0; i < str.length; i+=2) {
|
||||
console.log(sentence);
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
}
|
||||
printManyTimes("freeCodeCamp");
|
||||
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
|
||||
function printManyTimes(str) {
|
||||
const FCC = "freeCodeCamp";
|
||||
let fact = "is cool!";
|
||||
|
||||
const SENTENCE = str + " is cool!";
|
||||
for (let i = 0; i < str.length; i+=2) {
|
||||
console.log(SENTENCE);
|
||||
}
|
||||
|
||||
}
|
||||
printManyTimes("freeCodeCamp");
|
||||
fact = "is awesome!";
|
||||
console.log(FCC, fact);
|
||||
```
|
||||
|
@ -9,21 +9,27 @@ dashedName: declare-string-variables
|
||||
|
||||
# --description--
|
||||
|
||||
之前我们写过这样的代码:
|
||||
之前,你使用以下代码声明变量:
|
||||
|
||||
```js
|
||||
var myName;
|
||||
```
|
||||
|
||||
但是你也可以像这样声明一个字符串变量:
|
||||
|
||||
```js
|
||||
var myName = "your name";
|
||||
```
|
||||
|
||||
`"your name"` 被称作<dfn>字符串</dfn><dfn>字面量</dfn>。 这是一个字符串,因为它是一系列包含在单引号或双引号中的零或多个字符。
|
||||
`"your name"` 被称为 <dfn>string</dfn> <dfn>literal</dfn>。 字符串文字或字符串是用单引号或双引号括起来的一系列零个或多个字符。
|
||||
|
||||
# --instructions--
|
||||
|
||||
创建两个新的字符串变量:`myFirstName` 和 `myLastName`,并用你的姓和名分别为它们赋值。
|
||||
创建两个新的字符串变量:`myFirstName` 和 `myLastName`,并分别为它们分配你的名字和姓氏的值。
|
||||
|
||||
# --hints--
|
||||
|
||||
`myFirstName` 应该是一个字符串,至少包含一个字符。
|
||||
`myFirstName` 应该是一个至少包含一个字符的字符串。
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -41,7 +47,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myLastName` 应该是一个字符串,至少包含一个字符。
|
||||
`myLastName` 应该是一个至少包含一个字符的字符串。
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -8,55 +8,53 @@ dashedName: explore-differences-between-the-var-and-let-keywords
|
||||
|
||||
# --description--
|
||||
|
||||
使用 `var` 关键字来声明变量,会出现重复声明导致变量被覆盖却不会报错的问题。
|
||||
使用 `var` 关键字声明变量的最大问题之一是你可以轻松覆盖变量声明:
|
||||
|
||||
```js
|
||||
var camper = 'James';
|
||||
var camper = 'David';
|
||||
var camper = "James";
|
||||
var camper = "David";
|
||||
console.log(camper);
|
||||
```
|
||||
|
||||
这里控制台将显示字符串 `David`。
|
||||
在上面的代码中,`camper` 变量最初声明为 `James`,然后被覆盖为 `David`。 然后控制台显示字符串 `David`。
|
||||
|
||||
在上面的代码中,`camper` 变量的初始值为 `James`,然后又被覆盖成了 `David`。 在小型的应用中,你可能不会遇到这样的问题。但是当你的代码规模变得更加庞大的时候,就可能会在不经意间覆盖了之前定义的变量。 因为这样的情况不会报错,所以搜索和修复 bug 会变得非常困难。
|
||||
在 ES6 中引入了新的关键字 `let` 来解决 `var` 关键字带来的潜在问题。 如果你在上面的代码中使用 `let` 关键字来代替 `var` 关键字,结果会是一个报错。
|
||||
在小型应用程序中,你可能不会遇到此类问题。 但是随着你的代码库变大,你可能会意外地覆盖一个你不打算覆盖的变量。 由于此行为不会引发错误,因此搜索和修复错误变得更加困难。
|
||||
|
||||
ES6 中引入了一个名为 `let` 的关键字,这是对 JavaScript 的一次重大更新,以解决与 `var` 关键字有关的潜在问题。 你将在后面的挑战中了解其他 ES6 特性。
|
||||
|
||||
如果将上面代码中的 `var` 替换为 `let` ,则会导致错误:
|
||||
|
||||
```js
|
||||
let camper = 'James';
|
||||
let camper = 'David';
|
||||
let camper = "James";
|
||||
let camper = "David";
|
||||
```
|
||||
|
||||
你可以在浏览器的控制台里看见这个错误。 与 `var` 不同的是,当使用 `let` 的时候,同一名字的变量只能被声明一次。 请注意 `"use strict"`。 这代表着开启了严格模式,用于检测常见的代码错误以及“不安全”的行为, 例如:
|
||||
该错误可以在你的浏览器控制台中看到。
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
x = 3.14;
|
||||
```
|
||||
|
||||
这将显示一个错误 `x is not defined`。
|
||||
所以不像 `var`,当你使用 `let` 时,同名的变量只能声明一次。
|
||||
|
||||
# --instructions--
|
||||
|
||||
请更新这段代码,只使用 `let` 关键字。
|
||||
更新代码,使其仅使用 `let` 关键字。
|
||||
|
||||
# --hints--
|
||||
|
||||
代码中不应有 `var`
|
||||
`var` 不应存在于代码中。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/var/g));
|
||||
```
|
||||
|
||||
`catName` 变量的值应该为 `Oliver`
|
||||
`catName` 应该是字符串 `Oliver`。
|
||||
|
||||
```js
|
||||
assert(catName === 'Oliver');
|
||||
```
|
||||
|
||||
`quote` 变量的值应该为 `Oliver says Meow!`
|
||||
`catSound` 应该是字符串 `Meow!`
|
||||
|
||||
```js
|
||||
assert(quote === 'Oliver says Meow!');
|
||||
assert(catSound === 'Meow!');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -64,28 +62,13 @@ assert(quote === 'Oliver says Meow!');
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var catName;
|
||||
var quote;
|
||||
function catTalk() {
|
||||
"use strict";
|
||||
|
||||
catName = "Oliver";
|
||||
quote = catName + " says Meow!";
|
||||
|
||||
}
|
||||
catTalk();
|
||||
var catName = "Oliver";
|
||||
var catSound = "Meow!";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let catName;
|
||||
let quote;
|
||||
function catTalk() {
|
||||
'use strict';
|
||||
|
||||
catName = 'Oliver';
|
||||
quote = catName + ' says Meow!';
|
||||
}
|
||||
catTalk();
|
||||
let catName = "Oliver";
|
||||
let catSound = "Meow!";
|
||||
```
|
||||
|
@ -17,7 +17,7 @@ console.log("Alan Peter".length);
|
||||
|
||||
字符串 `10` 将会出现在控制台中。
|
||||
|
||||
例如,如果我们创建了一个变量 `var firstName = "Ada"`,我们就可以通过使用 `firstName.length` 属性来获得字符串 `Ada` 的长度。
|
||||
例如,如果我们创建了一个变量 `const firstName = "Ada"`,我们可以通过使用 `firstName.length` 找出字符串 `Ada` 的长度属性。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -29,8 +29,8 @@ console.log("Alan Peter".length);
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/var lastNameLength = 0;/) &&
|
||||
code.match(/var lastName = "Lovelace";/)
|
||||
code.match(/let lastNameLength = 0;/) &&
|
||||
code.match(/const lastName = "Lovelace";/)
|
||||
);
|
||||
```
|
||||
|
||||
@ -52,18 +52,17 @@ assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
let lastNameLength = 0;
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
lastNameLength = lastName;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
let lastNameLength = 0;
|
||||
const lastName = "Lovelace";
|
||||
lastNameLength = lastName.length;
|
||||
```
|
||||
|
@ -11,13 +11,13 @@ dashedName: global-scope-and-functions
|
||||
|
||||
在 JavaScript 中,<dfn>作用域</dfn>涉及到变量的作用范围。 在函数外定义的变量具有 <dfn>全局</dfn> 作用域。 这意味着,具有全局作用域的变量可以在代码的任何地方被调用。
|
||||
|
||||
这些没有使用 `var` 关键字定义的变量,会被自动创建在 `global` 作用域中,形成全局变量。 当在代码其他地方无意间定义了一个变量,刚好变量名与全局变量相同,这时会产生意想不到的后果。 因此你应该总是使用 `var` 关键字来声明你的变量。
|
||||
未使用 `let` 或 `const` 关键字声明的变量会在 `global` 范围内自动创建。 当在代码其他地方无意间定义了一个变量,刚好变量名与全局变量相同,这时会产生意想不到的后果。 你应该总是用 `let` 或 `const` 声明你的变量。
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `var`,在函数外声明一个全局变量 `myGlobal`, 并给它一个初始值 `10`。
|
||||
使用 `let` 或 `const`,在任何函数之外声明一个名为 `myGlobal` 的全局变量。 并给它一个初始值 `10`。
|
||||
|
||||
在函数 `fun1` 的内部,***不***使用 `var` 关键字,声明 `oopsGlobal`,并给它赋值为 `5`。
|
||||
在函数 `fun1` 中,***不要*** 使用 `let` 或 `const` 关键字,将 `5` 分配给 `oopsGlobal` 。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -33,10 +33,10 @@ assert(typeof myGlobal != 'undefined');
|
||||
assert(myGlobal === 10);
|
||||
```
|
||||
|
||||
应使用 `var` 关键字定义 `myGlobal`。
|
||||
`myGlobal` 应该使用 `let` 或 `const` 关键字声明
|
||||
|
||||
```js
|
||||
assert(/var\s+myGlobal/.test(code));
|
||||
assert(/(let|const)\s+myGlobal/.test(code));
|
||||
```
|
||||
|
||||
`oopsGlobal` 应为全局变量,值为 `5`。
|
||||
@ -109,7 +109,7 @@ function fun2() {
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myGlobal = 10;
|
||||
const myGlobal = 10;
|
||||
|
||||
function fun1() {
|
||||
oopsGlobal = 5;
|
||||
|
@ -14,13 +14,14 @@ dashedName: iterate-odd-numbers-with-a-for-loop
|
||||
初始化 `i = 0`,当 `i < 10` 的时候继续循环。 `i += 2` 让 `i` 每次循环之后增加 2。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 10; i += 2) {
|
||||
const ourArray = [];
|
||||
|
||||
for (let i = 0; i < 10; i += 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
循环结束后,`ourArray` 的值为 `[0,2,4,6,8]`。 改变计数器(`initialization`) ,这样我们可以用奇数来递增。
|
||||
`ourArray` 现在将包含 `[0, 2, 4, 6, 8]`。 改变计数器(`initialization`) ,这样我们可以用奇数来递增。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -34,7 +35,7 @@ for (var i = 0; i < 10; i += 2) {
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` 应该等于 `[1,3,5,7,9]`
|
||||
`myArray` 应该等于 `[1, 3, 5, 7, 9]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
||||
@ -52,16 +53,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 10; i += 2) {
|
||||
const myArray = [];
|
||||
for (let i = 1; i < 10; i += 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
@ -15,7 +15,7 @@ JavaScript 中最常见的循环就是 `for`,它可以循环指定次数。
|
||||
|
||||
for 循环中的可选三个表达式用分号隔开:
|
||||
|
||||
`for (a; b; c)`,其中 `a` 为初始化语句,`b` 是循环条件语句,`c` 是终止循环条件表达式。
|
||||
`for (a; b; c)`,其中`a`为初始化语句,`b`为条件语句,`c` 是最终的表达式。
|
||||
|
||||
初始化语句只会在执行循环开始之前执行一次。 它通常用于定义和设置你的循环变量。
|
||||
|
||||
@ -26,13 +26,14 @@ for 循环中的可选三个表达式用分号隔开:
|
||||
在下面的例子中,先初始化 `i = 0`,条件 `i < 5` 为 true 时,进入循环。 每次循环后 `i` 的值增加 `1`,然后执行终止循环条件表达式 `i++`。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 5; i++) {
|
||||
const ourArray = [];
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
最终 `ourArray` 的值为 `[0,1,2,3,4]`.
|
||||
`ourArray` 现在的值为 `[0, 1, 2, 3, 4]`。
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -64,16 +65,17 @@ if (typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 6; i++) {
|
||||
const myArray = [];
|
||||
for (let i = 1; i < 6; i++) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
@ -14,8 +14,9 @@ dashedName: iterate-with-javascript-while-loops
|
||||
我们将学习的第一种类型的循环称为 `while` 循环,当 while 指定的条件为真,循环才会执行,反之不执行。
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 0;
|
||||
const ourArray = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < 5) {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
@ -56,16 +57,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 5;
|
||||
const myArray = [];
|
||||
let i = 5;
|
||||
while (i >= 0) {
|
||||
myArray.push(i);
|
||||
i--;
|
||||
|
@ -16,8 +16,8 @@ dashedName: manipulate-arrays-with-pop
|
||||
数组中任何类型的元素(数值,字符串,甚至是数组)都可以被弹出来 。
|
||||
|
||||
```js
|
||||
var threeArr = [1, 4, 6];
|
||||
var oneDown = threeArr.pop();
|
||||
const threeArr = [1, 4, 6];
|
||||
const oneDown = threeArr.pop();
|
||||
console.log(oneDown);
|
||||
console.log(threeArr);
|
||||
```
|
||||
@ -26,7 +26,7 @@ console.log(threeArr);
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `.pop()` 函数移除 `myArray` 中的最后一个元素,并且把弹出的值赋给 `removedFromMyArray`。
|
||||
使用 `.pop()` 函数从 `myArray` 中删除最后一项,并将取出的值分配给新变量 `removedFromMyArray`。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -69,22 +69,22 @@ assert(
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
if (typeof removedFromMyArray !== 'undefined') (function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
const myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
var removedFromMyArray = myArray.pop();
|
||||
const myArray = [["John", 23], ["cat", 2]];
|
||||
const removedFromMyArray = myArray.pop();
|
||||
```
|
||||
|
@ -16,15 +16,15 @@ dashedName: manipulate-arrays-with-shift
|
||||
示例:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", ["cat"]];
|
||||
var removedFromOurArray = ourArray.shift();
|
||||
const ourArray = ["Stimpson", "J", ["cat"]];
|
||||
const removedFromOurArray = ourArray.shift();
|
||||
```
|
||||
|
||||
`removedFromOurArray` 值为 `Stimpson`,`ourArray` 值为 `["J", ["cat"]]`
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `.shift()` 函数移除 `myArray` 中的第一项,并把移出的值赋给 `removedFromMyArray`。
|
||||
使用 `.shift()` 函数从 `myArray` 中删除第一项,并将“移除的值”值分配给新变量 `removedFromMyArray`。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -65,24 +65,24 @@ assert(
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
if (typeof removedFromMyArray !== 'undefined') (function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray = myArray.shift();
|
||||
const removedFromMyArray = myArray.shift();
|
||||
```
|
||||
|
@ -16,7 +16,7 @@ dashedName: manipulate-arrays-with-unshift
|
||||
示例:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", "cat"];
|
||||
const ourArray = ["Stimpson", "J", "cat"];
|
||||
ourArray.shift();
|
||||
ourArray.unshift("Happy");
|
||||
```
|
||||
@ -25,7 +25,7 @@ ourArray.unshift("Happy");
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用 `unshift()` 函数把 `["Paul",35]` 加入到 `myArray` 的头部。
|
||||
使用 `unshift()` 将 `["Paul", 35]` 添加到 `myArray` 变量的开头。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -63,16 +63,17 @@ assert(
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
myArray.unshift(["Paul", 35]);
|
||||
```
|
||||
|
@ -9,12 +9,12 @@ dashedName: modify-array-data-with-indexes
|
||||
|
||||
# --description--
|
||||
|
||||
与字符串的数据不可变不同,数组的数据是可变的( <dfn>mutable</dfn>),可以自由地改变。
|
||||
与字符串不同,数组的条目是 <dfn>可变的</dfn> 并且可以自由更改,即使数组是用 `const` 声明的。
|
||||
|
||||
**示例**
|
||||
|
||||
```js
|
||||
var ourArray = [50,40,30];
|
||||
const ourArray = [50, 40, 30];
|
||||
ourArray[0] = 15;
|
||||
```
|
||||
|
||||
@ -28,7 +28,7 @@ ourArray[0] = 15;
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` 应该等于 `[45,64,99]`。
|
||||
`myArray` 现在应该是 `[45, 64, 99]`。
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -73,14 +73,15 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [18,64,99];
|
||||
const myArray = [18, 64, 99];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [18,64,99];
|
||||
const myArray = [18, 64, 99];
|
||||
myArray[0] = 45;
|
||||
```
|
||||
|
@ -12,11 +12,12 @@ dashedName: nesting-for-loops
|
||||
如果你有一个二维数组,可以使用相同的逻辑,先遍历外面的数组,再遍历里面的子数组。 下面是一个例子:
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
const arr = [
|
||||
[1, 2], [3, 4], [5, 6]
|
||||
];
|
||||
for (var i=0; i < arr.length; i++) {
|
||||
for (var j=0; j < arr[i].length; j++) {
|
||||
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
for (let j = 0; j < arr[i].length; j++) {
|
||||
console.log(arr[i][j]);
|
||||
}
|
||||
}
|
||||
@ -66,7 +67,7 @@ assert(
|
||||
|
||||
```js
|
||||
function multiplyAll(arr) {
|
||||
var product = 1;
|
||||
let product = 1;
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
@ -80,14 +81,12 @@ multiplyAll([[1,2],[3,4],[5,6,7]]);
|
||||
|
||||
```js
|
||||
function multiplyAll(arr) {
|
||||
var product = 1;
|
||||
for (var i = 0; i < arr.length; i++) {
|
||||
for (var j = 0; j < arr[i].length; j++) {
|
||||
let product = 1;
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
for (let j = 0; j < arr[i].length; j++) {
|
||||
product *= arr[i][j];
|
||||
}
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
multiplyAll([[1,2],[3,4],[5,6,7]]);
|
||||
```
|
||||
|
@ -13,13 +13,13 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
|
||||
|
||||
大多数现代编程语言,如 JavaScript,不同于人类从 1 开始计数。 它们是从 0 开始计数。 这被称为基于零(<dfn>Zero-based</dfn>)的索引。
|
||||
|
||||
例如,单词 `Charles` 的索引 0 的字符是 `C`。 所以在 `var firstName = "Charles"` 中,你可以使用 `firstName[0]` 来获得第一个位置上的字符。
|
||||
例如,单词 `Charles` 的索引 0 的字符是 `C`。 所以如果 `const firstName = "Charles"`,你可以通过 `firstName[0]` 得到字符串第一个字母的值。
|
||||
|
||||
示例:
|
||||
|
||||
```js
|
||||
var firstName = "Charles";
|
||||
var firstLetter = firstName[0];
|
||||
const firstName = "Charles";
|
||||
const firstLetter = firstName[0];
|
||||
```
|
||||
|
||||
`firstLetter` 值为字符串 `C` 。
|
||||
@ -56,8 +56,8 @@ assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
let firstLetterOfLastName = "";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName; // Change this line
|
||||
@ -66,8 +66,8 @@ firstLetterOfLastName = lastName; // Change this line
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
let firstLetterOfLastName = "";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName[0];
|
||||
|
@ -11,13 +11,13 @@ dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
|
||||
|
||||
要获取字符串的最后一个字符,可以用字符串的长度减 1 的索引值。
|
||||
|
||||
例如,如果 `var firstName = "Ada"` 中,那么你可以通过 `firstName[firstName.length - 1]` 来得到字符串的最后的一个字符。
|
||||
例如,如果 `const firstName = "Ada"`,则可以使用 `firstName[firstName.length - 1]` 获取字符串最后一个字母的值。
|
||||
|
||||
示例:
|
||||
|
||||
```js
|
||||
var firstName = "Ada";
|
||||
var lastLetter = firstName[firstName.length - 1];
|
||||
const firstName = "Ada";
|
||||
const lastLetter = firstName[firstName.length - 1];
|
||||
```
|
||||
|
||||
`lastLetter` 值为字符串 `a`。
|
||||
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var lastLetterOfLastName = lastName; // Change this line
|
||||
const lastLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var lastLetterOfLastName = lastName[lastName.length - 1];
|
||||
const lastName = "Lovelace";
|
||||
const lastLetterOfLastName = lastName[lastName.length - 1];
|
||||
```
|
||||
|
@ -11,13 +11,13 @@ dashedName: use-bracket-notation-to-find-the-nth-to-last-character-in-a-string
|
||||
|
||||
我们既可以获取字符串的最后一个字符,也可以用获取字符串的倒数第 N 个字符。
|
||||
|
||||
例如,你可以通过 `firstName[firstName.length - 3]` 来获得 `var firstName = "Augusta"` 字符串中的倒数第三个字符。
|
||||
例如,你可以使用 `firstName[firstName.length - 3]` 获取 `const firstName = "Augusta"` 字符串的倒数第三个字母的值
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
var firstName = "Augusta";
|
||||
var thirdToLastLetter = firstName[firstName.length - 3];
|
||||
const firstName = "Augusta";
|
||||
const thirdToLastLetter = firstName[firstName.length - 3];
|
||||
```
|
||||
|
||||
`thirdToLastLetter` 的值应该为字符串 `s`。
|
||||
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var secondToLastLetterOfLastName = lastName; // Change this line
|
||||
const secondToLastLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var secondToLastLetterOfLastName = lastName[lastName.length - 2];
|
||||
const lastName = "Lovelace";
|
||||
const secondToLastLetterOfLastName = lastName[lastName.length - 2];
|
||||
```
|
||||
|
@ -9,7 +9,7 @@ dashedName: use-conditional-logic-with-if-statements
|
||||
|
||||
# --description--
|
||||
|
||||
`If` 语句用于在代码中做条件判断。 关键字 `if` 告诉 JavaScript 在小括号中的条件为真的情况下去执行定义在大括号里面的代码。 这种条件被称为 `Boolean` 条件,因为他们只可能是 `true`(真)或 `false`(假)。
|
||||
`if` 语句用于在代码中做出决定。 关键字 `if` 告诉 JavaScript 在小括号中的条件为真的情况下去执行定义在大括号里面的代码。 这种条件被称为 `Boolean` 条件,因为他们只可能是 `true`(真)或 `false`(假)。
|
||||
|
||||
当条件的计算结果为 `true`,程序执行大括号内的语句。 当布尔条件的计算结果为 `false`,大括号内的代码将不会执行。
|
||||
|
||||
@ -26,6 +26,7 @@ function test (myCondition) {
|
||||
}
|
||||
return "It was false";
|
||||
}
|
||||
|
||||
test(true);
|
||||
test(false);
|
||||
```
|
||||
|
@ -8,11 +8,13 @@ dashedName: compare-scopes-of-the-var-and-let-keywords
|
||||
|
||||
# --description--
|
||||
|
||||
使用 `var` 关键字来声明一个变量的时候,这个变量会被声明成全局变量,或是函数内的局部变量。
|
||||
如果你不熟悉 `let`,请查看 [这个挑战](/learn/javascript-algorithms-and-data-structures/basic-javascript/explore-differences-between-the-var-and-let-keywords)。
|
||||
|
||||
`let` 关键字的作用与此类似,但会有一些额外的特性。 如果在代码块、语句或表达式中使用关键字 `let` 声明变量,这个变量的作用域就被限制在当前的代码块、语句或表达式之中。
|
||||
使用 `var` 关键字声明变量时,它是全局声明的,如果在函数内部声明则是局部声明的。
|
||||
|
||||
举个例子:
|
||||
`let` 关键字的行为类似,但有一些额外的功能。 在代码块、语句或表达式中使用 `let` 关键字声明变量时,其作用域仅限于该代码块、语句或表达式。
|
||||
|
||||
例如:
|
||||
|
||||
```js
|
||||
var numArray = [];
|
||||
@ -23,9 +25,9 @@ console.log(numArray);
|
||||
console.log(i);
|
||||
```
|
||||
|
||||
这里控制台将显示值 `[0, 1, 2]` 和 `3`。
|
||||
此处控制台将显示值 `[0, 1, 2]` 和 `3`。
|
||||
|
||||
因为使用了 `var` 关键字,`i` 被声明为全局变量。 所以当 `i++` 执行时,它会更新全局变量。 这个代码和下方的代码类似:
|
||||
使用 `var` 关键字,`i` 是全局声明的。 所以当 `i++` 被执行时,它会更新全局变量。 此代码类似于以下内容:
|
||||
|
||||
```js
|
||||
var numArray = [];
|
||||
@ -37,9 +39,9 @@ console.log(numArray);
|
||||
console.log(i);
|
||||
```
|
||||
|
||||
这里控制台将显示值 `[0, 1, 2]` 和 `3`。
|
||||
此处控制台将显示值 `[0, 1, 2]` 和 `3`。
|
||||
|
||||
如果你创建一个函数,将它存储起来,稍后在使用 `i` 变量的 `for` 循环中使用。这么做可能会出现问题。 这是因为存储的函数会总是指向更新后的全局 `i` 变量的值。
|
||||
如果你创建一个函数,将它存储起来,稍后在使用 `i` 变量的 `for` 循环中使用。这么做可能会出现问题。 这是因为存储的函数将始终引用更新后的全局 `i` 变量的值。
|
||||
|
||||
```js
|
||||
var printNumTwo;
|
||||
@ -53,9 +55,9 @@ for (var i = 0; i < 3; i++) {
|
||||
console.log(printNumTwo());
|
||||
```
|
||||
|
||||
这里控制台将显示值 `3`。
|
||||
此处控制台将显示值 `3`。
|
||||
|
||||
可以看到,`printNumTwo()` 打印了 3,而不是 2。 这是因为赋值给 `i` 的值已经更新,`printNumTwo()` 返回全局的 `i`,而不是在 for 循环中创建函数时 `i` 的值。 `let` 关键字就不会出现这种现象:
|
||||
可以看到,`printNumTwo()` 打印了 3 而不是 2。 这是因为赋值给 `i` 的值已经更新,`printNumTwo()` 返回全局的 `i`,而不是在 for 循环中创建函数时 `i` 的值。 `let` 关键字就不会出现这种现象:
|
||||
|
||||
```js
|
||||
let printNumTwo;
|
||||
@ -72,7 +74,7 @@ console.log(i);
|
||||
|
||||
在这里控制台将显示值 `2` 和一个错误提示 `i is not defined`。
|
||||
|
||||
`i` 未定义,因为它没有在全局范围内声明。 它只在 `for` 循环语句中被声明。 `printNumTwo()` 返回了正确的值,因为 `let` 关键字在循环语句中使 `i` 变量产生了三个不同的值(分别为 0、1、2)。
|
||||
`i` 未定义,因为它没有在全局范围内声明。 它只在 `for` 循环语句中被声明。 `printNumTwo()` 返回了正确的值,因为 `let` 关键字创建了三个具有唯一值(0、1 和 2)的不同 `i` 变量在循环语句中。
|
||||
|
||||
# --instructions--
|
||||
|
||||
|
@ -8,11 +8,13 @@ dashedName: mutate-an-array-declared-with-const
|
||||
|
||||
# --description--
|
||||
|
||||
在现代的 JavaScript 里,`const` 声明有很多用法。
|
||||
如果你不熟悉 `const`,请查看[这个挑战](/learn/javascript-algorithms-and-data-structures/basic-javascript/declare-a-read-only-variable-with-the-const-keyword)。
|
||||
|
||||
一些开发者倾向于默认使用 `const` 来声明所有变量,除非他们打算后续重新给变量赋值, 那么他们在声明的时候就会用 `let`。
|
||||
`const` 声明在现代 JavaScript 中有很多用例。
|
||||
|
||||
然而,你要注意,对象(包括数组和函数)在使用 `const` 声明的时候依然是可变的。 使用 `const` 来声明只会保证变量不会被重新赋值。
|
||||
默认情况下,一些开发人员更喜欢使用 `const` 分配所有变量,除非他们知道需要重新分配值。 只有在这种情况下,他们才使用 `let`。
|
||||
|
||||
但是,重要的是要了解使用 `const` 分配给变量的对象(包括数组和函数)仍然是可变的。 使用 `const` 声明只能防止变量标识符的重新分配。
|
||||
|
||||
```js
|
||||
const s = [5, 6, 7];
|
||||
@ -21,13 +23,13 @@ s[2] = 45;
|
||||
console.log(s);
|
||||
```
|
||||
|
||||
`s = [1, 2, 3]` 会导致一个错误。 `console.log` 会显示值 `[5, 6, 45]`。
|
||||
`s = [1, 2, 3]` 将导致错误。 `console.log` 将显示值 `[5, 6, 45]`。
|
||||
|
||||
可以发现,你可以改变对象 `[5, 6, 7]` 本身,而变量 `s` 会指向改变后的数组 `[5, 6, 45]`。 和所有数组一样,数组 `s` 中的元素是可以被改变的,但是因为使用了 `const` 关键字,你不能使用赋值操作符将变量标识 `s` 指向另外一个数组。
|
||||
如你所见,你可以改变对象 `[5, 6, 7]` 本身,变量 `s` 仍将指向更改后的数组 `[5, 6, 45]`。 像所有数组一样,`s` 中的数组元素是可变的,但是因为使用了 `const`,所以不能使用变量标识符 `s` 来指向一个使用赋值运算符的不同数组。
|
||||
|
||||
# --instructions--
|
||||
|
||||
这里有一个使用 `const s = [5, 7, 2]` 声明的数组。 使用对各元素赋值的方法将数组改成 `[2, 5, 7]`。
|
||||
数组声明为 `const s = [5, 7, 2]`。 使用对各元素赋值的方法将数组改成 `[2, 5, 7]`。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -37,7 +39,7 @@ console.log(s);
|
||||
(getUserInput) => assert(getUserInput('index').match(/const/g));
|
||||
```
|
||||
|
||||
`s` 应该为常量(使用 `const`)。
|
||||
`s` 应该是一个常量变量(通过使用 `const`)。
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/const\s+s/g));
|
||||
|
@ -10,7 +10,7 @@ dashedName: refactor-global-variables-out-of-functions
|
||||
|
||||
目前为止,我们已经看到了函数式编程的两个原则:
|
||||
|
||||
1) 不要更改变量或对象 - 创建新变量和对象,并在需要时从函数返回它们。 提示:使用类似 `var newArr = arrVar` 时 `arrVar` 是一个数组,代码只是创建一个对现有变量的引用,而不是副本。 所以更改 `newArr` 中的值会同时更改 `arrVar` 中的值。
|
||||
1) 不要更改变量或对象 - 创建新变量和对象,并在需要时从函数返回它们。 提示:使用类似 `const newArr = arrVar` 的东西,其中 `arrVar` 是一个数组,只会创建对现有变量的引用,而不是副本。 所以更改 `newArr` 中的值会同时更改 `arrVar` 中的值。
|
||||
|
||||
2) 声明函数参数 - 函数内的任何计算仅取决于参数,而不取决于任何全局对象或变量。
|
||||
|
||||
@ -86,7 +86,7 @@ assert(
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
// Change code below this line
|
||||
function add (bookName) {
|
||||
@ -99,7 +99,7 @@ function add (bookName) {
|
||||
|
||||
// Change code below this line
|
||||
function remove (bookName) {
|
||||
var book_index = bookList.indexOf(bookName);
|
||||
const book_index = bookList.indexOf(bookName);
|
||||
if (book_index >= 0) {
|
||||
|
||||
bookList.splice(book_index, 1);
|
||||
@ -109,9 +109,9 @@ function remove (bookName) {
|
||||
}
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
const newBookList = add(bookList, 'A Brief History of Time');
|
||||
const newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
const newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
|
||||
console.log(bookList);
|
||||
```
|
||||
@ -120,7 +120,7 @@ console.log(bookList);
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
function add(bookList, bookName) {
|
||||
return [...bookList, bookName];
|
||||
@ -135,7 +135,7 @@ function remove (bookList, bookName) {
|
||||
return bookListCopy;
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
const newBookList = add(bookList, 'A Brief History of Time');
|
||||
const newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
const newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
```
|
||||
|
@ -55,7 +55,7 @@ assert(code.match(/\s*\.\s*filter/g));
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
|
||||
```
|
||||
|
||||
`filteredList` 应等于 `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`。
|
||||
`filteredList` 应该等于 `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"}, {"title": "Batman Begins", "rating": "8.3"}]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(filteredList, [
|
||||
@ -72,7 +72,7 @@ assert.deepEqual(filteredList, [
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -187,7 +187,7 @@ var watchList = [
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var filteredList;
|
||||
const filteredList = "";
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
@ -197,8 +197,7 @@ console.log(filteredList);
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -311,7 +310,5 @@ var watchList = [
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
let filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
|
||||
// Only change code above this line
|
||||
const filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
|
||||
```
|
||||
|
@ -61,7 +61,7 @@ assert(!code.match(/for\s*?\([\s\S]*?\)/));
|
||||
assert(code.match(/\.map/g));
|
||||
```
|
||||
|
||||
`ratings` 应等于 `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`。
|
||||
`ratings` 应该等于 `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"},{"title": "Batman Begins", "rating": "8.3"}, {"title": "Avatar", "rating": "7.9"}]`。
|
||||
|
||||
```js
|
||||
assert.deepEqual(ratings, [
|
||||
@ -79,7 +79,7 @@ assert.deepEqual(ratings, [
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -194,8 +194,8 @@ var watchList = [
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var ratings = [];
|
||||
for(var i=0; i < watchList.length; i++){
|
||||
const ratings = [];
|
||||
for (let i = 0; i < watchList.length; i++) {
|
||||
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
|
||||
}
|
||||
|
||||
@ -207,8 +207,7 @@ console.log(JSON.stringify(ratings));
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -321,7 +320,7 @@ var watchList = [
|
||||
}
|
||||
];
|
||||
|
||||
var ratings = watchList.map(function(movie) {
|
||||
const ratings = watchList.map(function(movie) {
|
||||
return {
|
||||
title: movie["Title"],
|
||||
rating: movie["imdbRating"]
|
||||
|
@ -8,22 +8,86 @@ dashedName: budget-app
|
||||
|
||||
# --description--
|
||||
|
||||
Crie uma classe Category que pode ser usada para criar diferentes categorias de orçamento.
|
||||
|
||||
Você pode acessar [a descrição completa do projeto e o código inicial no Replit](https://replit.com/github/freeCodeCamp/boilerplate-budget-app).
|
||||
|
||||
Depois de ir para esse link, faça fork no projeto. Depois que você completar o projeto com baseado nas instruções do 'README.md', envie o link do seu projeto abaixo.
|
||||
Você [trabalhará neste projeto com nosso código inicial do Replit](https://replit.com/github/freeCodeCamp/boilerplate-budget-app).
|
||||
|
||||
Ainda estamos desenvolvendo a parte instrucional interativa do currículo Python. Por enquanto, aqui estão alguns vídeos no canal do freeCodeCamp.org do YouTube que ensinarão tudo o que você precisa saber para completar este projeto:
|
||||
|
||||
<ul>
|
||||
<li>
|
||||
<a href='https://www.freecodecamp.org/news/python-for-everybody/'>Curso de Python em vídeo para todos</a> (14 horas)
|
||||
</li>
|
||||
<li>
|
||||
<a href='https://www.freecodecamp.org/news/learn-python-basics-in-depth-video-course/'>Curso em vídeo Aprenda Python</a> (2 horas)
|
||||
</li>
|
||||
</ul>
|
||||
- [Curso de Python em vídeo para todos](https://www.freecodecamp.org/news/python-for-everybody/) (14 horas)
|
||||
|
||||
- [Curso Aprenda Python em vídeo](https://www.freecodecamp.org/news/learn-python-video-course/) (10 horas)
|
||||
|
||||
# --instructions--
|
||||
|
||||
Complete a classe `Category` no `budget.py`. Ela deve ser capaz de instanciar objetos com base em diferentes categorias de orçamento, como *alimentos* (food), *vestuário* (clothing) e *entretenimento* (entertainment). Quando os objetos são criados, eles são passados com o nome da categoria. A classe deve ter uma variável de instância chamada `ledger` que seja uma lista. A classe também deve conter os seguintes métodos:
|
||||
|
||||
- Um método`deposit`, que aceita um valor e uma descrição. Se nenhuma descrição for dada, o padrão deverá ser uma string vazia. O método deve acrescentar um objeto à lista ledger na forma de `{"amount": amount, "description": description}`.
|
||||
- Um método `withdraw`, semelhante ao método `deposit`, mas a quantia passada deve ser armazenada no ledger como um número negativo. Se não houver fundos suficientes, nada deve ser adicionado ao ledger. Este método deve retornar `True` se a retirada acontecer e, caso contrário, `False`.
|
||||
- Um método `get_balance`, que retorna o saldo atual da categoria de orçamento com base nos depósitos e retiradas que ocorreram.
|
||||
- Um método `transfer`, que aceita um valor e outra categoria de orçamento como argumentos. O método deverá adicionar uma retirada com o valor e a descrição "Transfer to [categoria de destino no orçamento]". O método deve, então, adicionar um depósito à outra categoria do orçamento, com o valor e a descrição "Transfer from [categoria de origem no orçamento]". Se não houver fundos suficientes, nada deve ser adicionado ao ledger. Este método deve retornar `True` se a transferência acontecer e, caso contrário, `False`.
|
||||
- Um método `check_funds` que aceita um valor como um argumento. Ele retorna `False` se o valor for maior que o saldo da categoria do orçamento e, caso contrário, retorna `True`. Este método deve ser usado tanto pelo método `withdraw` como pelo método `transfer`.
|
||||
|
||||
Quando o objeto de orçamento for impresso, ele deve mostrar:
|
||||
|
||||
- Uma linha com título de 30 caracteres em que o nome da categoria é centralizado em uma linha com `*` caracteres.
|
||||
- Uma lista dos itens no ledger. Cada linha deve mostrar a descrição e o valor. Os primeiros 23 caracteres da descrição devem ser exibidos e, depois, o valor. O valor deve estar alinhado corretamente, conter duas casas decimais e exibir um máximo de 7 caracteres.
|
||||
- Uma linha que exibe o total da categoria.
|
||||
|
||||
Aqui está um exemplo de resultado:
|
||||
|
||||
```bash
|
||||
*************Food*************
|
||||
initial deposit 1000.00
|
||||
groceries -10.15
|
||||
restaurant and more foo -15.89
|
||||
Transfer to Clothing -50.00
|
||||
Total: 923.96
|
||||
```
|
||||
|
||||
Além da classe `Category`, crie uma função (fora da classe) chamada `create_spend_chart`, que recebe uma lista de categorias como um argumento. Ela deve retornar uma string, que é um gráfico de barras.
|
||||
|
||||
O gráfico deve mostrar a porcentagem gasta em cada categoria passada para a função. A porcentagem gasta deve ser calculada apenas com retiradas, não com depósitos. No lado esquerdo do gráfico, deve haver rótulos de 0 a 100. As "barras" no gráfico de barras devem ser feitas com o caractere "o". A altura de cada barra deve ser arredondada para baixo para o 10 mais próximo. A linha horizontal abaixo das barras deve ir dois espaços além da barra final. O nome de cada categoria deve ser escrito verticalmente abaixo da barra. Deve haver um título no topo que diz "Percentage spent by category" (Porcentagem gasta por categoria).
|
||||
|
||||
Esta função será testada com até quatro categorias.
|
||||
|
||||
Olhe atentamente para o exemplo de resultado abaixo e certifique-se de que o espaçamento do resultado corresponde exatamente ao exemplo.
|
||||
|
||||
```bash
|
||||
Percentage spent by category
|
||||
100|
|
||||
90|
|
||||
80|
|
||||
70|
|
||||
60| o
|
||||
50| o
|
||||
40| o
|
||||
30| o
|
||||
20| o o
|
||||
10| o o o
|
||||
0| o o o
|
||||
----------
|
||||
F C A
|
||||
o l u
|
||||
o o t
|
||||
d t o
|
||||
h
|
||||
i
|
||||
n
|
||||
g
|
||||
```
|
||||
|
||||
Os testes unitários para este projeto estão em `test_module.py`.
|
||||
|
||||
## Desenvolvimento
|
||||
|
||||
Escreva seu código em `budget.py`. Para o desenvolvimento, você pode usar `main.py` para testar sua classe `Category`. Clique no botão "Run" e `main.py` será executado.
|
||||
|
||||
## Testes
|
||||
|
||||
Importamos os testes de `test_module.py` em `main.py` para a sua conveniência. Os testes serão executados automaticamente sempre que você clicar no botão "Run".
|
||||
|
||||
## Envio
|
||||
|
||||
Copie o URL do seu projeto e envie-o para o freeCodeCamp.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3ec1000cf542c50fefe
|
||||
title: 'Problem 127: abc-hits'
|
||||
title: 'Problema 127: Trio abc'
|
||||
challengeType: 5
|
||||
forumTopicId: 301754
|
||||
dashedName: problem-127-abc-hits
|
||||
@ -8,38 +8,32 @@ dashedName: problem-127-abc-hits
|
||||
|
||||
# --description--
|
||||
|
||||
The radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 23 × 32 × 7, so rad(504) = 2 × 3 × 7 = 42.
|
||||
O radical de $n$, $rad(n)$, é o produto dos fatores primos distintos de $n$. Por exemplo, $504 = 2^3 × 3^2 × 7$, então $rad(504) = 2 × 3 × 7 = 42$.
|
||||
|
||||
We shall define the triplet of positive integers (a, b, c) to be an abc-hit if:
|
||||
Definiremos o trio de números inteiros positivos (a, b, c) como sendo um trio abc se:
|
||||
|
||||
GCD(a, b) = GCD(a, c) = GCD(b, c) = 1
|
||||
1. $GCD(a, b) = GCD(a, c) = GCD(b, c) = 1$
|
||||
2. $a < b$
|
||||
3. $a + b = c$
|
||||
4. $rad(abc) < c$
|
||||
|
||||
a < b
|
||||
Por exemplo, (5, 27, 32) é um trio abc, pois:
|
||||
|
||||
a + b = c
|
||||
1. $GCD(5, 27) = GCD(5, 32) = GCD(27, 32) = 1$
|
||||
2. $5 < 27$
|
||||
3. $5 + 27 = 32$
|
||||
4. $rad(4320) = 30 < 32$
|
||||
|
||||
rad(abc) < c
|
||||
Ocorre que os trios abc são bastante raros e há somente 31 deles para $c < 1000$, com a $\sum{c} = 12523$.
|
||||
|
||||
For example, (5, 27, 32) is an abc-hit, because:
|
||||
|
||||
GCD(5, 27) = GCD(5, 32) = GCD(27, 32) = 1
|
||||
|
||||
5 < 27
|
||||
|
||||
5 + 27 = 32
|
||||
|
||||
rad(4320) = 30 < 32
|
||||
|
||||
It turns out that abc-hits are quite rare and there are only thirty-one abc-hits for c < 1000, with ∑c = 12523.
|
||||
|
||||
Find ∑c for c < 120000.
|
||||
Encontre a $\sum{c}$ para $c < 120000$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler127()` should return 18407904.
|
||||
`abcHits()` deve retornar `18407904`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler127(), 18407904);
|
||||
assert.strictEqual(abcHits(), 18407904);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -47,12 +41,12 @@ assert.strictEqual(euler127(), 18407904);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler127() {
|
||||
function abcHits() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler127();
|
||||
abcHits();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3ec1000cf542c50feff
|
||||
title: 'Problem 128: Hexagonal tile differences'
|
||||
title: 'Problema 128: Diferenças de blocos hexagonais'
|
||||
challengeType: 5
|
||||
forumTopicId: 301755
|
||||
dashedName: problem-128-hexagonal-tile-differences
|
||||
@ -8,18 +8,30 @@ dashedName: problem-128-hexagonal-tile-differences
|
||||
|
||||
# --description--
|
||||
|
||||
A hexagonal tile with number 1 is surrounded by a ring of six hexagonal tiles, starting at "12 o'clock" and numbering the tiles 2 to 7 in an anti-clockwise direction.
|
||||
Um bloco hexagonal com o número 1 é cercado por um anel de seis blocos hexagonais, começando às "12 horas" e numerando os blocos de 2 a 7 em direção anti-horária.
|
||||
|
||||
New rings are added in the same fashion, with the next rings being numbered 8 to 19, 20 to 37, 38 to 61, and so on. The diagram below shows the first three rings.
|
||||
Novos anéis são adicionados da mesma forma, com os próximos anéis sendo numerados de 8 a 19, 20 a 37, 38 a 61, e assim por diante. O diagrama abaixo mostra os três primeiros anéis.
|
||||
|
||||
By finding the difference between tile n and each of its six neighbours we shall define PD(n) to be the number of those differences which are prime. For example, working clockwise around tile 8 the differences are 12, 29, 11, 6, 1, and 13. So PD(8) = 3. In the same way, the differences around tile 17 are 1, 17, 16, 1, 11, and 10, hence PD(17) = 2. It can be shown that the maximum value of PD(n) is 3. If all of the tiles for which PD(n) = 3 are listed in ascending order to form a sequence, the 10th tile would be 271. Find the 2000th tile in this sequence.
|
||||
<img class="img-responsive center-block" alt="três primeiros anéis de blocos hexagonais dispostos com números de 1 a 37 e com os blocos 8 e 17 destacados" src="https://cdn.freecodecamp.org/curriculum/project-euler/hexagonal-tile-differences.png" style="background-color: white; padding: 10px;" />
|
||||
|
||||
Ao calcular a diferença entre o bloco $n$ e cada um de seus seis vizinhos, definiremos $PD(n)$ como o número dessas diferenças primas, que são primos.
|
||||
|
||||
Por exemplo, trabalhando no sentido horário em torno do bloco 8, as diferenças são 12, 29, 11, 6, 1 e 13. Portanto, $PD(8) = 3$.
|
||||
|
||||
Da mesma forma, as diferenças em torno do bloco 17 são 1, 17, 16, 1, 11 e 10. Portanto, $PD(17) = 2$.
|
||||
|
||||
Pode-se ser mostrar que o valor máximo de $PD(n)$ é $3$.
|
||||
|
||||
Se todos os blocos para os quais $PD(n) = 3$ estiverem listados em ordem ascendente para formar uma sequência, o décimo bloco seria 271.
|
||||
|
||||
Encontre o 2000º bloco desta sequência.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler128()` should return 14516824220.
|
||||
`hexagonalTile()` deve retornar `14516824220`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler128(), 14516824220);
|
||||
assert.strictEqual(hexagonalTile(), 14516824220);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -27,12 +39,12 @@ assert.strictEqual(euler128(), 14516824220);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler128() {
|
||||
function hexagonalTile() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler128();
|
||||
hexagonalTile();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3ef1000cf542c50ff01
|
||||
title: 'Problem 129: Repunit divisibility'
|
||||
title: 'Problema 129: Divisibilidade de repunits'
|
||||
challengeType: 5
|
||||
forumTopicId: 301756
|
||||
dashedName: problem-129-repunit-divisibility
|
||||
@ -8,20 +8,20 @@ dashedName: problem-129-repunit-divisibility
|
||||
|
||||
# --description--
|
||||
|
||||
A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111.
|
||||
Em inglês, um número que consiste apenas de 1s é chamado de repunit. Definiremos $R(k)$ como sendo um repunit de comprimento $k$. Por exemplo, $R(6) = 111111$.
|
||||
|
||||
Given that n is a positive integer and GCD(n, 10) = 1, it can be shown that there always exists a value, k, for which R(k) is divisible by n, and let A(n) be the least such value of k; for example, A(7) = 6 and A(41) = 5.
|
||||
Dado que $n$ é um número inteiro positivo e que o máximo divisor comum $GCD(n, 10) = 1$, pode-se mostrar que sempre existe um valor, $k$, para o qual $R(k)$ é divisível por $n$. Além disso, consideremos $A(n)$ o menor dos valores de $k$ (por exemplo, $A(7) = 6$ e $A(41) = 5$).
|
||||
|
||||
The least value of n for which A(n) first exceeds ten is 17.
|
||||
O menor valor de $n$ para o qual o $A(n)$ excede dez é 17.
|
||||
|
||||
Find the least value of n for which A(n) first exceeds one-million.
|
||||
Encontre o menor valor de $n$ para o qual $A(n)$ excede um milhão.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler129()` should return 1000023.
|
||||
`repunitDivisibility()` deve retornar `1000023`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler129(), 1000023);
|
||||
assert.strictEqual(repunitDivisibility(), 1000023);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -29,12 +29,12 @@ assert.strictEqual(euler129(), 1000023);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler129() {
|
||||
function repunitDivisibility() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler129();
|
||||
repunitDivisibility();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3ee1000cf542c50ff00
|
||||
title: 'Problem 130: Composites with prime repunit property'
|
||||
title: 'Problema 130: Compostos com propriedade de primo repunit'
|
||||
challengeType: 5
|
||||
forumTopicId: 301758
|
||||
dashedName: problem-130-composites-with-prime-repunit-property
|
||||
@ -8,22 +8,22 @@ dashedName: problem-130-composites-with-prime-repunit-property
|
||||
|
||||
# --description--
|
||||
|
||||
A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111.
|
||||
Em inglês, um número que consiste apenas de 1s é chamado de repunit. Definiremos $R(k)$ como sendo um repunit de comprimento $k$. Por exemplo, $R(6) = 111111$.
|
||||
|
||||
Given that n is a positive integer and GCD(n, 10) = 1, it can be shown that there always exists a value, k, for which R(k) is divisible by n, and let A(n) be the least such value of k; for example, A(7) = 6 and A(41) = 5.
|
||||
Dado que $n$ é um número inteiro positivo e que o máximo divisor comum $GCD(n, 10) = 1$, pode-se mostrar que sempre existe um valor, $k$, para o qual $R(k)$ é divisível por $n$. Além disso, consideremos $A(n)$ o menor dos valores de $k$ (por exemplo, $A(7) = 6$ e $A(41) = 5$).
|
||||
|
||||
You are given that for all primes, p > 5, that p − 1 is divisible by A(p). For example, when p = 41, A(41) = 5, and 40 is divisible by 5.
|
||||
Você é informado, para todos os números primos, $p > 5$, que $p − 1$ é divisível por $A(p)$. Por exemplo, quando $p = 41, A(41) = 5$ e 40 é divisível por 5.
|
||||
|
||||
However, there are rare composite values for which this is also true; the first five examples being 91, 259, 451, 481, and 703.
|
||||
No entanto, há valores compostos raros para os quais isto também é verdadeiro. Os cinco primeiros exemplos são 91, 259, 451, 481 e 703.
|
||||
|
||||
Find the sum of the first twenty-five composite values of n for whichGCD(n, 10) = 1 and n − 1 is divisible by A(n).
|
||||
Encontre a soma dos primeiros vinte e cinco valores compostos de $n$ para os quais o máximo divisor comum, $GCD(n, 10) = 1$, e $n - 1$ é divisível por $A(n)$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler130()` should return 149253.
|
||||
`compositeRepunit()` deve retornar `149253`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler130(), 149253);
|
||||
assert.strictEqual(compositeRepunit(), 149253);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -31,12 +31,12 @@ assert.strictEqual(euler130(), 149253);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler130() {
|
||||
function compositeRepunit() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler130();
|
||||
compositeRepunit();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3f21000cf542c50ff04
|
||||
title: 'Problem 133: Repunit nonfactors'
|
||||
title: 'Problema 133: Não fatores repunit'
|
||||
challengeType: 5
|
||||
forumTopicId: 301761
|
||||
dashedName: problem-133-repunit-nonfactors
|
||||
@ -8,20 +8,20 @@ dashedName: problem-133-repunit-nonfactors
|
||||
|
||||
# --description--
|
||||
|
||||
A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111.
|
||||
Em inglês, um número que consiste apenas de 1s é chamado de repunit. Definiremos $R(k)$ como sendo um repunit de comprimento $k$. Por exemplo, $R(6) = 111111$.
|
||||
|
||||
Let us consider repunits of the form R(10n).
|
||||
Vamos considerar os repunits no formato $R({10}^n)$.
|
||||
|
||||
Although R(10), R(100), or R(1000) are not divisible by 17, R(10000) is divisible by 17. Yet there is no value of n for which R(10n) will divide by 19. In fact, it is remarkable that 11, 17, 41, and 73 are the only four primes below one-hundred that can be a factor of R(10n).
|
||||
Embora $R(10)$, $R(100)$ ou $R(1000)$ não sejam divisíveis por 17, $R(10000)$ é. No entanto, não há valor de n para o qual $R({10}^n)$ seja divisível por 19. Curiosamente, 11, 17, 41 e 73 são os únicos quatro primos abaixo de cem que podem ser um fator de $R({10}^n)$.
|
||||
|
||||
Find the sum of all the primes below one-hundred thousand that will never be a factor of R(10n).
|
||||
Encontre a soma de todos os primos abaixo de cem mil que nunca serão um fator de $R({10}^n)$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler133()` should return 453647705.
|
||||
`repunitNonfactors()` deve retornar `453647705`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler133(), 453647705);
|
||||
assert.strictEqual(repunitNonfactors(), 453647705);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -29,12 +29,12 @@ assert.strictEqual(euler133(), 453647705);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler133() {
|
||||
function repunitNonfactors() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler133();
|
||||
repunitNonfactors();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3f21000cf542c50ff05
|
||||
title: 'Problem 134: Prime pair connection'
|
||||
title: 'Problema 134: Conexão de pares de números primos'
|
||||
challengeType: 5
|
||||
forumTopicId: 301762
|
||||
dashedName: problem-134-prime-pair-connection
|
||||
@ -8,18 +8,18 @@ dashedName: problem-134-prime-pair-connection
|
||||
|
||||
# --description--
|
||||
|
||||
Consider the consecutive primes p1 = 19 and p2 = 23. It can be verified that 1219 is the smallest number such that the last digits are formed by p1 whilst also being divisible by p2.
|
||||
Considere os primos consecutivos $p_1 = 19$ e $p_2 = 23$. É possível verificar que 1219 é o menor número, tal que os últimos algarismos são formados por $p_1$, ao mesmo tempo em que são divisíveis por $p_2$.
|
||||
|
||||
In fact, with the exception of p1 = 3 and p2 = 5, for every pair of consecutive primes, p2 > p1, there exist values of n for which the last digits are formed by p1 and n is divisible by p2. Let S be the smallest of these values of n.
|
||||
De fato, com exceção de $p_1 = 3$ e $p_2 = 5$, para cada par de números primos consecutivos, $p_2 > p_1$, existem valores de $n$ para os quais os últimos algarismos são formados por $p_1$ e $n$ é divisível por $p_2$. Considere $S$ o menor destes valores de $n$.
|
||||
|
||||
Find ∑ S for every pair of consecutive primes with 5 ≤ p1 ≤ 1000000.
|
||||
Encontre $\sum{S}$ para cada par de números primos consecutivos, com $5 ≤ p_1 ≤ 1000000$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler134()` should return 18613426663617120.
|
||||
`primePairConnection()` deve retornar `18613426663617120`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler134(), 18613426663617120);
|
||||
assert.strictEqual(primePairConnection(), 18613426663617120);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -27,12 +27,12 @@ assert.strictEqual(euler134(), 18613426663617120);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler134() {
|
||||
function primePairConnection() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler134();
|
||||
primePairConnection();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3f31000cf542c50ff06
|
||||
title: 'Problem 135: Same differences'
|
||||
title: 'Problema 135: Mesmas diferenças'
|
||||
challengeType: 5
|
||||
forumTopicId: 301763
|
||||
dashedName: problem-135-same-differences
|
||||
@ -8,20 +8,20 @@ dashedName: problem-135-same-differences
|
||||
|
||||
# --description--
|
||||
|
||||
Given the positive integers, x, y, and z, are consecutive terms of an arithmetic progression, the least value of the positive integer, n, for which the equation, x2 − y2 − z2 = n, has exactly two solutions is n = 27:
|
||||
Sendo os números inteiros positivos, $x$, $y$ e $z$, termos consecutivos de uma progressão aritmética, o menor valor do inteiro positivo, $n$, para o qual a equação, $x^2 - y^2 - z^2 = n$, tem exatamente duas soluções é $n = 27$:
|
||||
|
||||
342 − 272 − 202 = 122 − 92 − 62 = 27
|
||||
$$34^2 − 27^2 − 20^2 = 12^2 − 9^2 − 6^2 = 27$$
|
||||
|
||||
It turns out that n = 1155 is the least value which has exactly ten solutions.
|
||||
Ocorre que $n = 1155$ é o menor valor para o qual a equação tem exatamente dez soluções.
|
||||
|
||||
How many values of n less than one million have exactly ten distinct solutions?
|
||||
Quantos valores de $n$ abaixo de um milhão têm exatamente dez soluções distintas?
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler135()` should return 4989.
|
||||
`sameDifferences()` deve retornar `4989`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler135(), 4989);
|
||||
assert.strictEqual(sameDifferences(), 4989);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -29,12 +29,12 @@ assert.strictEqual(euler135(), 4989);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler135() {
|
||||
function sameDifferences() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler135();
|
||||
sameDifferences();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3cc1000cf542c50fede
|
||||
title: 'Problem 95: Amicable chains'
|
||||
title: 'Problema 95: Cadeias amigáveis'
|
||||
challengeType: 5
|
||||
forumTopicId: 302212
|
||||
dashedName: problem-95-amicable-chains
|
||||
@ -8,45 +8,45 @@ dashedName: problem-95-amicable-chains
|
||||
|
||||
# --description--
|
||||
|
||||
The proper divisors of a number are all the divisors excluding the number itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number.
|
||||
Os divisores apropriados de um número são todos os seus divisores excetuando o número em si. Por exemplo, os divisores adequados de 28 são 1, 2, 4, 7 e 14. Como a soma desses divisores é igual a 28, chamamos esse número de um número perfeito.
|
||||
|
||||
Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers. For this reason, 220 and 284 are called an amicable pair.
|
||||
Curiosamente, a soma dos divisores adequados de 220 é 284 e a soma dos divisores adequados de 284 é 220, formando uma cadeia de dois números. Por esta razão, 220 e 284 são chamados de par amigável.
|
||||
|
||||
Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers:
|
||||
Talvez menos conhecidas sejam as cadeias mais longas. Por exemplo, começando com 12496, formamos uma cadeia de cinco números:
|
||||
|
||||
$$ 12496 → 14288 → 15472 → 14536 → 14264 \\,(→ 12496 → \cdots) $$
|
||||
|
||||
Since this chain returns to its starting point, it is called an amicable chain.
|
||||
Como essa cadeia retorna ao seu ponto de partida, ela é chamada de uma cadeia amigável.
|
||||
|
||||
Find the smallest member of the longest amicable chain with no element exceeding `limit`.
|
||||
Encontre o menor membro da maior cadeia amigável sem elementos que excedam o `limit`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`amicableChains(300)` should return a number.
|
||||
`amicableChains(300)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof amicableChains(300) === 'number');
|
||||
```
|
||||
|
||||
`amicableChains(300)` should return `220`.
|
||||
`amicableChains(300)` deve retornar `220`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(amicableChains(300), 220);
|
||||
```
|
||||
|
||||
`amicableChains(15000)` should return `220`.
|
||||
`amicableChains(15000)` deve retornar `220`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(amicableChains(15000), 220);
|
||||
```
|
||||
|
||||
`amicableChains(100000)` should return `12496`.
|
||||
`amicableChains(100000)` deve retornar `12496`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(amicableChains(100000), 12496);
|
||||
```
|
||||
|
||||
`amicableChains(1000000)` should return `14316`.
|
||||
`amicableChains(1000000)` deve retornar `14316`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(amicableChains(1000000), 14316);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3ce1000cf542c50fee0
|
||||
title: 'Problem 97: Large non-Mersenne prime'
|
||||
title: 'Problema 97: Grande número primo que não seja de Mersenne'
|
||||
challengeType: 5
|
||||
forumTopicId: 302214
|
||||
dashedName: problem-97-large-non-mersenne-prime
|
||||
@ -8,39 +8,39 @@ dashedName: problem-97-large-non-mersenne-prime
|
||||
|
||||
# --description--
|
||||
|
||||
The first known prime found to exceed one million digits was discovered in 1999, and is a Mersenne prime of the form $2^{6972593} − 1$; it contains exactly 2,098,960 digits. Subsequently other Mersenne primes, of the form $2^p − 1$, have been found which contain more digits.
|
||||
O primeiro número primo descoberto que excedia um milhão de algarismos foi descoberto em 1999. Ele é um primo de Mersenne no formato $2^{6972593} - 1$ e contém exatamente 2.098.960 algarismos. Depois disso, outros primos de Mersenne, no formato $2^p - 1$, foram encontrados e contendo mais dígitos.
|
||||
|
||||
However, in 2004 there was found a massive non-Mersenne prime which contains 2,357,207 digits: $28433 × 2^{7830457} + 1$.
|
||||
No entanto, em 2004, foi encontrado um número primo enorme e não sendo um primo de Mersenne que contém 2.357.207 algarismos: $28433 × 2^{7830457} + 1$.
|
||||
|
||||
Find the last ten digits of that non-Mersenne prime in the form $multiplier × 2^{power} + 1$.
|
||||
Encontre os últimos dez dígitos daquele primo que não seja de Mersenne na forma $multiplicador × 2^{potência} + 1$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`largeNonMersennePrime(19, 6833086)` should return a string.
|
||||
`largeNonMersennePrime(19, 6833086)` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof largeNonMersennePrime(19, 6833086) === 'string');
|
||||
```
|
||||
|
||||
`largeNonMersennePrime(19, 6833086)` should return the string `3637590017`.
|
||||
`largeNonMersennePrime(19, 6833086)` deve retornar a string `3637590017`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largeNonMersennePrime(19, 6833086), '3637590017');
|
||||
```
|
||||
|
||||
`largeNonMersennePrime(27, 7046834)` should return the string `0130771969`.
|
||||
`largeNonMersennePrime(27, 7046834)` deve retornar a string `0130771969`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largeNonMersennePrime(27, 7046834), '0130771969');
|
||||
```
|
||||
|
||||
`largeNonMersennePrime(6679881, 6679881)` should return the string `4455386113`.
|
||||
`largeNonMersennePrime(6679881, 6679881)` deve retornar a string `4455386113`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largeNonMersennePrime(6679881, 6679881), '4455386113');
|
||||
```
|
||||
|
||||
`largeNonMersennePrime(28433, 7830457)` should return the string `8739992577`.
|
||||
`largeNonMersennePrime(28433, 7830457)` deve retornar a string `8739992577`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largeNonMersennePrime(28433, 7830457), '8739992577');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3cf1000cf542c50fee1
|
||||
title: 'Problem 98: Anagramic squares'
|
||||
title: 'Problema 98: Quadrados anagrâmicos'
|
||||
challengeType: 5
|
||||
forumTopicId: 302215
|
||||
dashedName: problem-98-anagramic-squares
|
||||
@ -8,35 +8,35 @@ dashedName: problem-98-anagramic-squares
|
||||
|
||||
# --description--
|
||||
|
||||
By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively, we form a square number: $1296 = 36^2$. What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a square number: $9216 = 96^2$. We shall call CARE (and RACE) a square anagram word pair and specify further that leading zeroes are not permitted, neither may a different letter have the same digital value as another letter.
|
||||
Ao substituir cada uma das letras na palavra CARE por 1, 2, 9 e 6, respectivamente, formamos um número quadrado: $1296 = 36^2$. O que é notável é que, usando as mesmas substituições digitais, o anagrama, RACE, também formamos um número quadrado: $9216 = 96^2$. Vamos chamar CARE (e RACE) de um par de palavras de anagrama quadrado. Especificaremos mais adiante que zeros à frente do número não são permitidos, nem uma outra letra pode ter o mesmo valor numérico que outra.
|
||||
|
||||
Using the `words` array, find all the square anagram word pairs (a palindromic word is NOT considered to be an anagram of itself).
|
||||
Usando o array `words`, encontre todos os pares de palavras que são anagramas quadrados (uma palavra palindrômica NÃO é considerada um anagrama de si mesmo).
|
||||
|
||||
What is the largest square number formed by any member of such a pair?
|
||||
Qual é o maior número quadrado formado por algum membro de um par desse tipo?
|
||||
|
||||
**Note:** All anagrams formed must be contained in the given `words` array.
|
||||
**Observação:** todos os anagramas formados devem estar contidos no array dado `words`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`anagramicSquares(['CARE', 'RACE'])` should return a number.
|
||||
`anagramicSquares(['CARE', 'RACE'])` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof anagramicSquares(['CARE', 'RACE']) === 'number');
|
||||
```
|
||||
|
||||
`anagramicSquares(['CARE', 'RACE'])` should return `9216`.
|
||||
`anagramicSquares(['CARE', 'RACE'])` deve retornar `9216`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(anagramicSquares(['CARE', 'RACE']), 9216);
|
||||
```
|
||||
|
||||
`anagramicSquares(testWords1)` should return `4761`.
|
||||
`anagramicSquares(testWords1)` deve retornar `4761`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(anagramicSquares(_testWords1), 4761);
|
||||
```
|
||||
|
||||
`anagramicSquares(testWords2)` should return `18769`.
|
||||
`anagramicSquares(testWords2)` deve retornar `18769`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(anagramicSquares(_testWords2), 18769);
|
||||
|
Reference in New Issue
Block a user