FCC Basic JS

Comment

第1种

1
//这是注释

第2种

1
2
/* 这是
注释 */

Variables

JS有7种数据类型:undefined, null, boolean, string, symbol, number, and object

定义变量

1
var 变量名

变量名不可以包含空格,也不可以以1个数字开始。

赋值

1
2
3
4
5
var a;
var b = 2;

var a = 7;
var b = a;

未初始化变量

When JavaScript variables are declared, they have an initial value of undefined.

If you do a mathematical operation on an undefinedvariable your result will be NaNwhich means “Not a Number”.

If you concatenate a string with an undefinedvariable, you will get a literal string of "undefined".

1
2
3
4
5
6
7
var a = 5;
var b = 10;
var c = "I am a";

a = a + 1;
b = b + 5;
c = c + " String!";

大小写敏感

MYVAR不等于 MyVar或者 myvar

Write variable names in JavaScript in camelCase.

In camelCase, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.

建议变量命名使用骆驼峰拼写法camelCase,第一个单词首字母小写,后面的单词首字母大写。

1
2
3
4
5
6
7
8
9
// Declarations
var studlyCapVar;
var properCamelCase;
var titleCaseOver;

// Assignments
studlyCapVar = 10;
properCamelCase = "A String";
titleCaseOver = 9000;

递增运算符

1
i++;

is the equivalent of

1
i = i + 1;
1
2
3
4
var myVar = 87;

// Only change code below this line
myVar++;

递减运算符

1
2
3
4
var myVar = 11;

// Only change code below this line
myVar--;

十进制数值 Decimal Numbers

Decimal numbers are sometimes referred to as floating pointnumbers or floats.

余数

The remainder operator is sometimes incorrectly referred to as the “modulus” operator.

It is very similar to modulus, but does not work properly with negative numbers.

1
2
var remainder;
remainder = 11 % 3;

复合赋值运算符

Augmented Addition

1
2
3
var myVar = 1;
myVar += 5;
console.log(myVar); // Returns 6
1
myVar = myVar + 5;
1
2
3
4
5
6
7
8
9
var a = 3;
var b = 17;
var c = 12;

// Only modify code below this line

a += 12;
b += 9;
c += 7;

Augmented Subtraction

1
myVar -= 5;
1
myVar = myVar - 5;

Augmented Multiplication

1
myVar *= 5;
1
myVar = myVar * 5;

Augmented Division

1
myVar /= 5;
1
myVar = myVar / 5;

转义引号

引号前面使用 反斜杠 (\) backslash 来转义引号。

1
var sampleStr = "Alan said, \"Peter is learning JavaScript\".";
1
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";

单引号

1
var myStr = '<a href="http://www.example.com" target="_blank">Link</a>';

转义序列列表

Code Output
\' single quote
\" double quote
\\ backslash(反斜杠符)
\n newline(换行符)
\r carriage return(回车符)
\t tab(制表符)
\b backspace(退格符)
\f form feed(换页符)

Note that the backslash itself must be escaped in order to display as a backslash.

如果你想要显示一个反斜杠就必须要转义它。

1
var myStr = 'FirstLine\n\t\\SecondLine\nThirdLine';

连接符

1
var myStr = "This is the start. " + "This is the end.";

长字符串

1
2
var myStr = "This is the first sentence. ";
myStr += "This is the second sentence.";

字符串值长度

.length属性

1
lastNameLength = lastName.length;

索引(Bracket Notation)

1
firstLetterOfLastName = lastName[0];

不可改变的字符串

In JavaScript, Stringvalues are immutable, which means that they cannot be altered once created.

改变 myStr 中的唯一方法是重新给它赋一个值,就像这样:

var myStr = “Bob”;
myStr = “Job”;

最后字符串

1
var lastLetterOfLastName = lastName[lastName.length - 1];

Word Blanks

1
2
3
4
5
6
7
8
9
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) 

{
var result = "";
result += "My "+myAdjective+" "+myNoun+" "+myVerb+" very "+myAdverb+".";
return result;
}

wordBlanks("dog", "big", "ran", "quickly");

列表

1
var sandwich = ["peanut butter", "jelly", "bread"]

nested array

1
var ourArray = [["the universe", 42], ["everything", 101010]];

Modify Array Data With Indexes

1
2
3
4
5
6
var ourArray = [18,64,99];
ourArray[1] = 45; // ourArray now equals [18,45,99].

// Setup
var myArray = [18,64,99];
myArray[0] = 45;

多维数组

1
2
3
4
5
6
7
8
9
var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[0]; // 等于 [1,2,3]
arr[1][2]; // 等于 6
arr[3][0][1]; // 等于 11

push函数

1
2
3
var arr = [1,2,3];
arr.push(4);
// arr is now [1,2,3,4]

pop函数

1
2
3
4
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6
console.log(threeArr); // Returns [1, 4]

shift函数

remove first

1
2
3
4
var ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift();

// removedFromOurArray now equals "Stimpson" and ourArray now equals ["J", ["cat"]].

unshift函数

向数组的开头添加元素

1
2
3
4
5
var ourArray = ["Stimpson", "J", "cat"];
ourArray.shift(); // ourArray now equals ["J", "cat"]
ourArray.unshift("Happy");

// ourArray now equals ["Happy", "J", "cat"]

Reusable Functions

1
2
3
function functionName() {
console.log("Hello World");
}

Passing Values to Functions with Arguments

1
2
3
function testFun(param1, param2) {
console.log(param1, param2);
}

Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or “passed”) into a function when it is called are known as arguments.

函数的参数parameters在函数中充当占位符(也叫形参)的作用,参数可以为一个或多个。调用一个函数时所传入的参数为实参,实参决定着形参真正的值。简单理解:形参即形式、实参即内容。

1
2
3
4
function functionWithArgs(a, b){
console.log(a + b);
}
functionWithArgs(1, 2);

Global Scope and Functions 全局作用域

In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.

Variables which are used without the varkeyword are automatically created in the globalscope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.

在 JavaScript 中, 作用域 涉及到变量的作用范围。在函数外定义的变量具有 全局 作用域。这意味着,具有全局作用域的变量可以在代码的任何地方被调用。

这些没有使用var关键字定义的变量,会被自动创建在全局作用域中,形成全局变量。当在代码其他地方无意间定义了一个变量,刚好变量名与全局变量相同,这时会产生意想不到的后果。因此你应该总是使用var关键字来声明你的变量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var myGlobal = 10;

function fun1() {
oopsGlobal = 5;
}

function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}

Local Scope and Functions

Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function.

在一个函数内声明的变量,以及该函数的参数都是局部变量,意味着它们只在该函数内可见。

这是在函数 myTest内声明局部变量loc 的最佳例子:

1
2
3
4
5
6
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined

locis not defined outside of the function.

在函数外,loc 是未定义的。

1
2
3
4
5
6
7
function myFunction() {
'use strict';

var myVar = "pikapika";
console.log(myVar);
}
myFunction();

Global vs. Local Scope in Functions

It is possible to have both local and global variables with the same name. When you do this, the localvariable takes precedence over the globalvariable.

一个程序中有可能具有相同名称的 局部 变量 和 全局变量。在这种情况下,局部 变量将会优先于 全局 变量。

In this example:

1
2
3
4
5
var someVar = "Hat";
function myFun() {
var someVar = "Head";
return someVar;
}

The function myFunwill return "Head"because the localversion of the variable is present.

函数 myFun 将会返回 "Head",因为 局部变量 优先级更高。

1
2
3
4
5
6
7
8
var outerWear = "T-Shirt";

function myOutfit() {
var outerWear = "sweater";
return outerWear;
}

myOutfit();

Return a Value from a Function with Return

We can pass values into a function with arguments. You can use a returnstatement to send a value back out of a function.

我们可以把数据通过函数的 参数 来传入函数,也可以使用 return 语句把数据从一个函数中传出来。

1
2
3
4
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // 8

plusThreetakes an argument for numand returns a value equal to num + 3.

plusThree 带有一个为 num 的 参数 并且返回(returns)一个等于 num + 3 的值。

1
2
3
4
5
6
7
8
9
10
function minusSeven(num) {
return num - 7;
}


function timesFive(num){
return num * 5;
}

console.log(minusSeven(10));

Understanding Undefined Value returned from a Function

A function can include the returnstatement but it does not have to. In the case that the function doesn’t have a returnstatement, when you call it, the function processes the inner code but the returned value is undefined.

1
2
3
4
5
var sum = 0;
function addSum(num) {
sum = sum + num;
}
var returnedValue = addSum(3); // sum will be modified but returned value is undefined

addSumis a function without a returnstatement. The function will change the global sumvariable but the returned value of the function is undefined

Create a function addFivewithout any arguments. This function adds 5 to the sumvariable, but its returned value is undefined.

1
2
3
4
5
6
7
8
9
10
11
var sum = 0;
function addThree() {
sum = sum + 3;
}


function addFive(){
sum += 5;
}

var returnedValue = addFive();

Assignment with a Returned Value

If you’ll recall from our discussion of Storing Values with the Assignment Operator, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.

如果你还记得我们在这一节 Storing Values with the Equal Operator 的讨论,赋值之前,先完成等号右边的操作。这意味着我们可把一个函数的返回值,赋值给一个变量。

Assume we have pre-defined a function sumwhich adds two numbers together, then:

假设我们预先定义的函数 sum 其功能就是将两个数字相加,那么:

1
ourSum = sum(5, 12);

will call sumfunction, which returns a value of 17and assigns it to ourSumvariable.

将调用 sum 函数,返回return了一个数值 17,然后把它赋值给了 ourSum 变量。

练习:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var changed = 0;

function change(num) {
return (num + 5) / 3;
}

changed = change(10);


var processed = 0;

function processArg(num) {
return (num + 3) / 5;
}


processed = processArg(7);

Stand in Line

In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queueand old items are taken off from the front of the queue.

Write a function nextInLinewhich takes an array (arr) and a number (item) as arguments.

Add the number to the end of the array, then remove the first element of the array.

The nextInLinefunction should then return the element that was removed.

在计算机科学中 队列(queue)是一个抽象的数据结构,队列中的条目都是有秩序的。新的条目会被加到 队列 的末尾,旧的条目会从 队列 的头部被移出。

写一个函数 queue ,用一个数组arr和一个数字item作为参数。数字item添加到数组的结尾,然后移出数组的第一个元素,最后队列函数应该返回被删除的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function nextInLine(arr, item) {
// Your code here
arr.push(item);
var item = arr.shift();
return item; // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

Boolean

Another data type is the Boolean. Booleansmay only be one of two values: trueor false. They are basically little on-off switches, where trueis “on” and falseis “off.” These two states are mutually exclusive.

另一种数据类型是布尔(Boolean)。布尔 值要么是true 要么是false。它非常像电路开关, true是“开”,false 是“关”。这两种状态是互斥的。

注意
Boolean 值绝不会写作被引号包裹起来的形式。字符串"true""false" 不是 布尔值,在 JavaScript 中也没有特殊含义。

Note
Booleanvalues are never written with quotes. The strings`“true”and“false”are notBoolean`and have no special meaning in JavaScript.

练习:

1
2
3
function welcomeToBooleans() {
return true;
}

If Statements

Ifstatements are used to make decisions in code. The keyword iftells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as Booleanconditions and they may only be trueor false.

When the condition evaluates to true, the program executes the statement inside the curly braces. When the Boolean condition evaluates to false, the statement inside the curly braces will not execute.

If 语句用于在代码中做条件判断。关键字 if 告诉 JavaScript 在小括号中的条件为真的情况下去执行定义在大括号里面的代码。这种条件被称为 Boolean 条件,因为他们只可能是 true(真)或 false(假)。

当条件的计算结果为 true,程序执行大括号内的语句。当布尔条件的计算结果为 false,大括号内的代码将不会执行。

Pseudocode

1
2
3
if (condition is true) {
statement is executed
}
1
2
3
4
5
6
7
8
function test (myCondition) {
if (myCondition) {
return "It was true";
}
return "It was false";
}
test(true); // returns "It was true"
test(false); // returns "It was false"

When testis called with a value of true, the ifstatement evaluates myConditionto see if it is trueor not. Since it is true, the function returns "It was true". When we call testwith a value of false, myConditionis not trueand the statement in the curly braces is not executed and the function returns "It was false".

test 被调用,并且传递进来的参数值为 trueif语句会计算 myCondition 的结果,看它是真还是假。如果条件为 true,函数会返回 "It was true"。当 test 被调用,并且传递进来的参数值为 falsemyCondition true,并且不执行大括号后面的语句,函数返回 "It was false"

练习:

Create an ifstatement inside the function to return "Yes, that was true"if the parameter wasThatTrueis trueand return "No, that was false"otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function ourTrueOrFalse(isItTrue) {
if (isItTrue) {
return "Yes, it's true";
}
return "No, it's false";
}

function trueOrFalse(wasThatTrue) {
if(wasThatTrue){
return "Yes, that was true";
}
return "No, that was false";
}

trueOrFalse(false);

Equality Operator 相等运算符

here are many Comparison Operators in JavaScript. All of these operators return a boolean trueor falsevalue.

The most basic operator is the equality operator ==. The equality operator compares two values and returns trueif they’re equivalent or falseif they are not. Note that equality is different from assignment (=), which assigns the value at the right of the operator to a variable in the left.

在 JavaScript 中,有很多 相互比较的操作。所有这些操作符都返回一个 truefalse 值。

最基本的运算符是相等运算符:==。相等运算符比较两个值,如果它们是同等,返回 true,如果它们不等,返回 false。值得注意的是相等运算符不同于赋值运算符(=),赋值运算符是把等号右边的值赋给左边的变量。

1
2
3
4
5
6
function equalityTest(myVal) {
if (myVal == 10) {
return "Equal";
}
return "Not Equal";
}

If myValis equal to 10, the equality operator returns true, so the code in the curly braces will execute, and the function will return "Equal". Otherwise, the function will return "Not Equal".

In order for JavaScript to compare two different data types(for example, numbersand strings), it must convert one type to another. This is known as “Type Coercion”. Once it does, however, it can compare terms as follows:

如果 myVal 等于 10,相等运算符会返回 true,因此大括号里面的代码会被执行,函数将返回 "Equal"。否则,函数返回 "Not Equal"

在 JavaScript 中,为了让两个不同的 数据类型(例如 数字字符串)的值可以作比较,它必须把一种类型转换为另一种类型。然而一旦这样做,它可以像下面这样来比较:

1
2
3
4
1 == 1 // true
1 == 2 // false
1 == '1' // true
"3" == 3 // true

练习:

1
2
3
4
5
6
7
8
function myTest(val) {
if (val == 12) {
return "Equal";
}
return "Not Equal";
}

myTest(10);

Strict Equality Operator 严格相等运算符

Strict equality (===) is the counterpart to the equality operator (==). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.

If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.

严格相等运算符(===)是相对于相等操作符(==)的一种操作符。与相等操作符不同的是,它会同时比较元素的值和 数据类型

Examples

1
2
3 === 3 // true
3 === '3' // false

In the second example, 3is a Numbertype and '3'is a Stringtype.

练习:

1
2
3
4
5
6
7
8
function testStrict(val) {
if (val === 7) {
return "Equal";
}
return "Not Equal";
}

testStrict(10);

Practice comparing different values

In the last two challenges, we learned about the equality operator (==) and the strict equality operator (===). Let’s do a quick review and practice using these operators some more.

If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.

1
2
3 == '3' // returns true because JavaScript performs type conversion from string to number
3 === '3' // returns false because the types are different and type conversion is not performed

Note
In JavaScript, you can determine the type of a variable or a value with the typeofoperator, as follows:

1
2
typeof 3 // returns 'number'
typeof '3' // returns 'string'

练习:

The compareEqualityfunction in the editor compares two values using the equality operator. Modify the function so that it returns “Equal” only when the values are strictly equal.

1
2
3
4
5
6
7
8
function compareEquality(a, b) {
if (a === b) {
return "Equal";
}
return "Not Equal";
}

compareEquality(10, "10");

Inequality Operator 不相等运算符

The inequality operator (!=) is the opposite of the equality operator. It means “Not Equal” and returns falsewhere equality would return trueand vice versa. Like the equality operator, the inequality operator will convert data types of values while comparing.

不相等运算符(!=)与相等运算符是相反的。这意味着不相等运算符中,如果“不为真”并且返回 false的地方,在相等运算符中会返回true反之亦然。与相等运算符类似,不相等运算符在比较的时候也会转换值的数据类型。

1
2
3
4
5
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
1
2
3
4
5
6
7
8
function testNotEqual(val) {
if (val != 99) {
return "Not Equal";
}
return "Equal";
}

testNotEqual(10);

Strict Inequality Operator 严格相等运算符

The strict inequality operator (!==) is the logical opposite of the strict equality operator. It means “Strictly Not Equal” and returns falsewhere strict equality would return trueand vice versa. Strict inequality will not convert data types.

严格相等运算符(===)是相对于相等操作符(==)的一种操作符。与相等操作符不同的是,它会同时比较元素的值和 数据类型

1
2
3 === 3   // true
3 === '3' // false

3 是一个 数字 类型的,而'3' 是一个 字符 类型的,所以3不全等于’3’。

the Greater Than Operator 大于运算符

The greater than operator (>) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns true. Otherwise, it returns false.

Like the equality operator, greater than operator will convert data types of values while comparing.

使用大于运算符(>)来比较两个数字。如果大于运算符左边的数字大于右边的数字,将会返回 true。否则,它返回 false

与相等运算符一样,大于运算符在比较的时候,会转换值的数据类型。

1
2
3
4
 5 > 3   // true
7 > '3' // true
2 > 3 // false
'1' > 9 // false

the Greater Than Or Equal To Operator 大于等于运算符

The greater than or equal tooperator (>=) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns true. Otherwise, it returns false.

Like the equality operator, greater than or equal tooperator will convert data types while comparing.

使用 大于等于 运算符(>=)来比较两个数字的大小。如果大于等于运算符左边的数字比右边的数字大或者相等,它会返回 true。否则,它会返回 false

与相等运算符相似,大于等于 运算符在比较的时候会转换值的数据类型。

1
2
3
4
 6  >=  6  // true
7 >= '3' // true
2 >= 3 // false
'7' >= 9 // false

the Less Than Operator 小于运算符

The less than operator (<) compares the values of two numbers. If the number to the left is less than the number to the right, it returns true. Otherwise, it returns false. Like the equality operator, less thanoperator converts data types while comparing.

使用 小于 运算符(<)比较两个数字的大小。如果小于运算符左边的数字比右边的数字小,它会返回 true。否则,他会返回 false。与相等运算符类似,小于 运算符在做比较的时候会转换值的数据类型。

1
2
3
4
5
2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false

the Less Than Or Equal To Operator 小于等于运算符

The less than or equal tooperator (<=) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns true. If the number on the left is greater than the number on the right, it returns false. Like the equality operator, less than or equal toconverts data types.

1
2
3
4
5
4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false

the Logical And Operator

Sometimes you will need to test more than one thing at a time. The logical and operator (&&) returns trueif and only if the operands to the left and right of it are true.

The same effect could be achieved by nesting an if statement inside another if:

有时你需要在一次判断中做多个操作。当且仅当运算符的左边和右边都是 true,逻辑与 运算符(&&)才会返回 true

1
2
3
4
5
6
if (num > 5) {
if (num < 10) {
return "Yes";
}
}
return "No";

will only return “Yes” if numis greater than 5and less than 10. The same logic can be written as:

只有当 num 的值在6和9之间(包括6和9)才会返回 “Yes”。相同的逻辑可被写为:

1
2
3
4
if (num > 5 && num < 10) {
return "Yes";
}
return "No";

the Logical Or Operator

The logical or operator (||) returns trueif either of the operands is true. Otherwise, it returns false.

如果任何一个操作数是true,逻辑或 运算符 (||) 返回 true。反之,返回 false

The logical or operator is composed of two pipe symbols (|). This can typically be found between your Backspace and Enter keys.

The pattern below should look familiar from prior waypoints:

1
2
3
4
5
6
7
if (num > 10) {
return "No";
}
if (num < 5) {
return "No";
}
return "Yes";

will return “Yes” only if numis between 5and 10(5 and 10 included). The same logic can be written as:

只有当num大于等于5或小于等于10时,函数返回”Yes”。相同的逻辑可以简写成:

1
2
3
4
if (num > 10 || num < 5) {
return "No";
}
return "Yes";

练习:

1
2
3
4
5
6
7
8
9
function testLogicalOr(val) {

if (val >= 21 || val < 10) {
return "Outside";
}
return "Inside";
}

testLogicalOr(15);

Introducing Else Statements

When a condition for an ifstatement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an elsestatement, an alternate block of code can be executed.

if语句的条件为真,大括号里的代码执行,那如果条件为假呢?

正常情况下什么也不会发生。

写一个else语句,当条件为假时执行相应的代码。

1
2
3
4
5
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
function testElse(val) {
var result = "";

if (val > 5) {
result = "Bigger than 5";
} else {
return "5 or Smaller";
}

return result;
}

testElse(4);

Else If Statements

If you have multiple conditions that need to be addressed, you can chain ifstatements together with else ifstatements.

如果你有多个条件语句,你可以通过else if语句把 if语句链起来。

1
2
3
4
5
6
7
if (num > 15) {
return "Bigger than 15";
} else if (num < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 15";
}
1
2
3
4
5
6
7
8
9
10
11
12
function testElseIf(val) {
if (val > 10) {
return "Greater than 10";
} else if (val < 5){
return "Smaller than 5";
} else {
return "Between 5 and 10";
}
}

// Change this value to test
testElseIf(7);

Logical Order in If Else Statements

Order is important in if, else ifstatements.

The function is executed from top to bottom so you will want to be careful of what statement comes first.

ifelse if语句中代码的执行顺序是很重要的。

在条件判断语句中,代码的执行顺序是从上到下,所以你需要考虑清楚先执行哪一句,后执行哪一句。

Take these two functions as an example.

Here’s the first:

1
2
3
4
5
6
7
8
9
function foo(x) {
if (x < 1) {
return "Less than one";
} else if (x < 2) {
return "Less than two";
} else {
return "Greater than or equal to two";
}
}

And the second just switches the order of the statements:

第二个例子更改了代码的执行顺序:

1
2
3
4
5
6
7
8
9
function bar(x) {
if (x < 2) {
return "Less than two";
} else if (x < 1) {
return "Less than one";
} else {
return "Greater than or equal to two";
}
}

While these two functions look nearly identical if we pass a number to both we get different outputs.

这两个函数看起来几乎一模一样,我们传一个值进去看看它们有什么区别。

1
2
foo(0) // "Less than one"
bar(0) // "Less than two"

练习:

1
2
3
4
5
6
7
8
9
10
11
12
function orderMyLogic(val) {
if (val < 5) {
return "Less than 5";
} else if (val < 10) {
return "Less than 10";
} else {
return "Greater than or equal to 10";
}
}

// Change this value to test
orderMyLogic(7);

Chaining If Else Statements

if/elsestatements can be chained together for complex logic. Here is pseudocode of multiple chained if/ else ifstatements:

if/else 语句串联在一起可以实现复杂的逻辑,这是多个if/else if 语句串联在一起的伪代码:

1
2
3
4
5
6
7
8
9
10
if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}

Write chained if/else ifstatements to fulfill the following conditions:

if/else if语句串联起来实现下面的逻辑:

num < 5- return “Tiny”
num < 10- return “Small”
num < 15- return “Medium”
num < 20- return “Large”
num >= 20- return “Huge”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function testSize(num) {
// Only change code below this line
if(num<5){
return "Tiny"
}else if(num<10){
return "Small"
}else if(num<15){
return "Medium"
}else if(num<20){
return "Large"
}else{
return "Huge"
}

return "Change Me";
// Only change code above this line
}

// Change this value to test
testSize(7);

Golf Code

In the game of golf each hole has a parmeaning the average number of strokesa golfer is expected to make in order to sink the ball in a hole to complete the play. Depending on how far above or below paryour strokesare, there is a different nickname.

Your function will be passed parand strokesarguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):

在高尔夫golf游戏中,每个洞都有自己的标准杆数par,代表着距离。根据你把球打进洞所挥杆的次数strokes,可以计算出你的高尔夫水平。

函数将会传送2个参数,分别是标准杆数par 和 挥杆次数strokes ,根据下面的表格返回正确的水平段位。

Strokes Return
1 “Hole-in-one!”
<= par - 2 “Eagle”
par - 1 “Birdie”
par “Par”
par + 1 “Bogey”
par + 2 “Double Bogey”
>= par + 3 “Go Home!”

parand strokeswill always be numeric and positive. We have added an array of all the names for your convenience.

parstrokes 必须是数字而且是正数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
// Only change code below this line
if (strokes === 1){
return "Hole-in-one!";
} else if (strokes <= par - 2){
return "Eagle";
} else if (strokes === par - 1) {
return "Birdie";
} else if (strokes === par) {
return "Par";
} else if (strokes === par + 1) {
return "Bogey";
} else if (strokes === par + 2) {
return "Double Bogey";
} else if (strokes >= par + 3) {
return "Go Home!";
}

return "Change Me";
// Only change code above this line
}

// Change these values to test
golfScore(5, 4);

Switch Statements

If you have many options to choose from, use a switchstatement. A switchstatement tests a value and can have many casestatements which define various possible values. Statements are executed from the first matched casevalue until a breakis encountered.

如果你有非常多的选项需要选择,可以使用switch语句。根据不同的参数值会匹配上不同的case分支,语句会从第一个匹配的case分支开始执行,直到碰到break就结束。

Here is a pseudocode example:

1
2
3
4
5
6
7
8
9
10
11
12
switch(num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}

casevalues are tested with strict equality (===). The breaktells JavaScript to stop executing statements. If the breakis omitted, the next statement will be executed.

测试case 值使用严格相等运算符进行比较,break关键字告诉javascript停止执行语句。如果没有break关键字,下一个语句会继续执行。


Write a switch statement which tests valand sets answerfor the following conditions:

写一个测试 val的switch语句,并且根据下面的条件来设置不同的answer

1- “alpha”
2- “beta”
3- “gamma”
4- “delta”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function caseInSwitch(val) {
var answer = "";
// Only change code below this line
switch (val){
case 1:
answer = "alpha";
break;
case 2:
answer = "beta";
break;
case 3:
answer = "gamma";
break;
case 4:
answer = "delta";
break;
}

// Only change code above this line
return answer;
}

// Change this value to test
caseInSwitch(1);

Adding a Default Option in Switch Statements

In a switchstatement you may not be able to specify all possible values as casestatements. Instead, you can add the defaultstatement which will be executed if no matching casestatements are found. Think of it like the final elsestatement in an if/elsechain.

switch 语句中你可能无法用case来指定所有情况,这时你可以添加default语句。当再也找不到case匹配的时候default语句会执行,非常类似于if/else组合中的else语句。

A defaultstatement should be the last case.

1
2
3
4
5
6
7
8
9
10
11
12
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}

Write a switch statement to set answerfor the following conditions:
"a"- “apple”
"b"- “bird”
"c"- “cat”
default- “stuff”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function myTest(val) {
var answer = "";

switch (val){
case "a":
answer = "apple";
break;
case "b":
answer = "bird";
break;
case "c":
answer = "cat";
break;

default:
answer = "stuff";
}

return answer;
}

myTest(1);

Multiple Identical Options in Switch Statements

If the breakstatement is omitted from a switchstatement’s case, the following casestatement(s) are executed until a breakis encountered. If you have multiple inputs with the same output, you can represent them in a switchstatement like this:

如果switch语句中的case分支的break 语句漏掉了,后面的 case语句会一直执行直到遇到break。如果你有多个输入值和输出值一样,可以试试下面的switch语句:

1
2
3
4
5
6
7
8
9
switch(val) {
case 1:
case 2:
case 3:
result = "1, 2, or 3";
break;
case 4:
result = "4 alone";
}

Cases for 1, 2, and 3 will all produce the same result.

分支1、2、3将会产生相同的输出结果。


Write a switch statement to set answerfor the following ranges:
1-3- “Low”
4-6- “Mid”
7-9- “High”

Note
You will need to have a casestatement for each number in the range.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function sequentialSizes(val) {
var answer = "";
// Only change code below this line
switch (val) {
case 1:
case 2:
case 3:
answer = "Low";
break;
case 4:
case 5:
case 6:
answer = "Mid";
break;
case 7:
case 8:
case 9:
answer = "High";
break;
}

// Only change code above this line
return answer;
}

// Change this value to test
sequentialSizes(1);

Replacing If Else Chains with Switch

If you have many options to choose from, a switchstatement can be easier to write than many chained if/else ifstatements. The following:

1
2
3
4
5
6
7
if (val === 1) {
answer = "a";
} else if (val === 2) {
answer = "b";
} else {
answer = "c";
}

can be replaced with:

1
2
3
4
5
6
7
8
9
10
switch(val) {
case 1:
answer = "a";
break;
case 2:
answer = "b";
break;
default:
answer = "c";
}

练习:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function chainToSwitch(val) {
var answer = "";
// Only change code below this line

switch (val) {
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
answer = "Ate Nine";
break;
default:
answer = "";
}

// Only change code above this line
return answer;
}

// Change this value to test
chainToSwitch(7);

Returning Boolean Values from Functions

You may recall from Comparison with the Equality Operator that all comparison operators return a boolean trueor falsevalue.

Sometimes people use an if/else statement to do a comparison, like this:

你可能会回想起Comparison with the Equality Operator ,所有的比较操作符返回的都是一个boolean值,要么是 true 要么是false

使用 if/else语句来做比较然后返回truefalse已经成为大家的共识:

1
2
3
4
5
6
7
function isEqual(a,b) {
if (a === b) {
return true;
} else {
return false;
}
}

But there’s a better way to do this. Since ===returns trueor false, we can return the result of the comparison:

因为=== 总是返回 truefalse,所以我们可以直接返回比较的结果:

1
2
3
function isEqual(a,b) {
return a === b;
}

练习:

1
2
3
4
5
6
function isLess(a, b) {
// Fix this code
return a < b;
}
// Change these values to test
isLess(10, 15);

Return Early Pattern for Functions

When a returnstatement is reached, the execution of the current function stops and control returns to the calling location.

当代码执行到return语句时,函数返回一个结果就结束运行了,return后面的语句根本不会执行。

1
2
3
4
5
6
function myFun() {
console.log("Hello");
return "World";
console.log("byebye")
}
myFun();

The above outputs “Hello” to the console, returns “World”, but "byebye"is never output, because the function exits at the returnstatement.

上面的代码输出”Hello”到控制台、返回 “World”,但没有输出"byebye",因为函数遇到return语句就退出了。


Modify the function abTestso that if aor bare less than 0the function will immediately exit with a value of undefined.

修改函数abTestab小于0时,函数立即返回一个undefined并退出。

Hint
Remember that undefinedis a keyword, not a string.

1
2
3
4
5
6
7
8
function abTest(a, b) {  
if (a < 0 || b <0)
return undefined;

return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}

abTest(2,2);

Counting Cards

In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called Card Counting.

Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.

在赌场21点游戏中,玩家可以通过计算牌桌上已经发放的卡牌的高低值来让自己在游戏中保持优势,这就叫21点算法

根据下面的表格,每张卡牌都分配了一个值。如果卡牌的值大于0,那么玩家应该追加赌注。反之,追加少许赌注甚至不追加赌注。

Count Change Cards
+1 2, 3, 4, 5, 6
0 7, 8, 9
-1 10, ‘J’, ‘Q’, ‘K’, ‘A’

You will write a card counting function. It will receive a cardparameter, which can be a number or a string, and increment or decrement the global countvariable according to the card’s value (see table). The function will then return a string with the current count and the string Betif the count is positive, or Holdif the count is zero or negative. The current count and the player’s decision (Betor Hold) should be separated by a single space.

你需要写一个函数,实现21点算法,它根据参数 card的值来递增或递减变量count,函数返回一个由当前count"Bet"(count>0)或"Hold"(count<=0) 拼接的字符串。注意count"Bet""Hold"应该用空格分开。

Example Output
-3 Hold
5 Bet

Hint
Do NOT reset countto 0 when value is 7, 8, or 9.
Do NOT return an array.
Do NOT include quotes (single or double) in the output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var count = 0;

function cc(card) {
switch(card){
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 10:
case "J":
case "Q":
case "K":
case "A":
count--;
break;
}
if (count > 0){
return count + " Bet";
} else {
return count + " Hold";
}

return "Change Me";
}

// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');

创建JS对象

对象和数组很相似,数组是通过索引来访问和修改数据,对象是通过属性来访问和修改数据的。

1
2
3
4
5
6
var cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};

In this example, all the properties are stored as strings, such as - "name", "legs", and "tails". However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:

1
2
3
4
5
var anotherObject = {
make: "Ford",
5: "five",
"model": "focus"
};

However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};

// Only change code below this line.

var myDog = {
"name": "Dong",
"legs": 2,
"tails": 1,
"friends":["wholeworld"]
};

Accessing Object Properties with Dot Notation

There are two ways to access the properties of an object: dot notation (.) and bracket notation ([]), similar to an array.

Dot notation is what you use when you know the name of the property you’re trying to access ahead of time.

Here is a sample of using dot notation (.) to read an object’s property:

有两种方式访问对象属性,一个是点操作符(.),一个是中括号操作符([])。

当你知道属性的名称的时候,使用点操作符。

这是一个使用点操作符读取对象属性的例子:

1
2
3
4
5
6
var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
1
2
3
4
5
6
7
8
9
10
var testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};

// Only change code below this line

var hatValue = testObj.hat; // Change this line
var shirtValue = testObj.shirt; // Change this line

Accessing Object Properties with Bracket Notation

The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.

However, you can still use bracket notation on object properties without spaces.

Here is a sample of using bracket notation to read an object’s property:

第二种访问对象的方式就是中括号操作符([]),如果你想访问的属性的名称有一个空格,这时你只能使用中括号操作符([])。

这是一个使用中括号操作符([])读取对象属性的例子:

1
2
3
4
5
6
7
8
var myObj = {
"Space Name": "Kirk",
"More Space": "Spock",
"NoSpace": "USS Enterprise"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock
myObj["NoSpace"]; // USS Enterprise

Note that property names with spaces in them must be in quotes (single or double).

1
2
3
4
5
6
7
8
var testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};

var entreeValue=testObj["an entree"];
var drinkValue=testObj["the drink"];

Accessing Object Properties with Variables

Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object’s properties or when accessing a lookup table.

Here is an example of using a variable to access a property:

中括号操作符的另一个使用方式是用变量来访问一个属性。当你需要遍历对象的属性列表或查表时,这种方式极为有用。

这有一个使用变量来访问属性的例子:

1
2
3
4
5
6
var dogs = {
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"

Another way you can use this concept is when the property’s name is collected dynamically during the program execution, as follows:

1
2
3
4
5
6
7
8
9
var someObj = {
propName: "John"
};
function propPrefix(str) {
var s = "prop";
return s + str;
}
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // "John"

Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name.

提示:当我们通过变量名访问属性的时候,不需要给变量名包裹引号。因为实际上我们使用的是变量的值,而不是变量的名称。

1
2
3
4
5
6
7
8
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};

var playerNumber = 16;
var player = testObj[playerNumber];

Updating Object Properties

After you’ve created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.

For example, let’s look at ourDog:

当你创建了一个对象后,你可以用点操作符或中括号操作符来更新对象的属性。

举个例子,让我们看看 ourDog:

1
2
3
4
5
6
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};

Since he’s a particularly happy dog, let’s change his name to “Happy Camper”. Here’s how we update his object’s name property:

让我们更改它的名称为 “Happy Camper”,这有两种方式来更新对象的name属性:

ourDog.name = "Happy Camper";or

1
ourDog["name"] = "Happy Camper";

Now when we evaluate ourDog.name, instead of getting “Camper”, we’ll get his new name, “Happy Camper”.

Add New Properties to a JavaScript Object

You can add new properties to existing JavaScript objects the same way you would modify them.

Here’s how we would add a "bark"property to ourDog:

你也可以像更改属性一样给对象添加属性。

看看我们是如何给ourDog添加 "bark"属性:

1
ourDog.bark = "bow-wow";

or

1
ourDog["bark"] = "bow-wow";

Now when we evaluate ourDog.bark, we’ll get his bark, “bow-wow”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Example
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};

ourDog.bark = "bow-wow";

// Setup
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};

// Only change code below this line.
myDog.bark = "woof";

Delete Properties from a JavaScript Object

We can also delete properties from objects like this:

1
delete ourDog.bark;

Using Objects for Lookups

Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to “lookup” values rather than a switchstatement or an if/elsechain. This is most useful when you know that your input data is limited to a certain range.

Here is an example of a simple reverse alphabet lookup:

对象和字典一样,可以用来存储键/值对。如果你的数据跟对象一样,你可以用对象来查找你想要的值,而不是使用switch或if/else语句。当你知道你的输入数据在某个范围时,这种查找方式极为有效。

这是简单的反向字母表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var alpha = {
1:"Z",
2:"Y",
3:"X",
4:"W",
...
24:"C",
25:"B",
26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"

var value = 2;
alpha[value]; // "Y"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function phoneticLookup(val) {
var result = "";

var lookup = {
alpha:"Adams",
bravo:"Boston",
charlie:"Chicago",
delta:"Denver",
echo:"Easy",
foxtrot:"Frank",
"":undefined
};

result = lookup[val];
return result;
}

phoneticLookup("charlie");

Testing Objects for Properties

Sometimes it is useful to check if the property of a given object exists or not. We can use the .hasOwnProperty(propname)method of objects to determine if that object has the given property name. .hasOwnProperty()returns trueor falseif the property is found or not.

有时检查一个对象属性是否存在是非常有用的,我们可以用.hasOwnProperty(propname)方法来检查对象是否有该属性。如果有返回true,反之返回 false

1
2
3
4
5
6
var myObj = {
top: "hat",
bottom: "pants"
};
myObj.hasOwnProperty("top"); // true
myObj.hasOwnProperty("middle"); // false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};

function checkObj(checkProp) {
if (myObj.hasOwnProperty(checkProp))

{
return myObj[checkProp];

} else {
return "Not Found";
}

}

checkObj("gift");

Manipulating Complex Objects

Sometimes you may want to store data in a flexible Data Structure. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects.

Here’s an example of a complex data structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
var ourMusic = [
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
];

This is an array which contains one object inside. The object has various pieces of metadata about an album. It also has a nested "formats"array. If you want to add more album records, you can do this by adding records to the top level array.

Objects hold data in a property, which has a key-value format. In the example above, "artist": "Daft Punk"is a property that has a key of "artist"and a value of "Daft Punk".

JavaScript Object Notation or JSONis a related data interchange format used to store data.

1
2
3
4
5
6
7
8
9
10
11
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}

Note
You will need to place a comma after every object in the array, unless it is the last object in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CS",
"8T",
"LP" ],
"gold": true
},

{
"artist": "Tsuyoshi Hiroshi",
"title": "Tonboyou",
"release_year": 1987,
"formats": [
"CD",
"DVD",
"LP"],
"gold": true
}
];

Accessing Nested Objects

通过串联起来的点操作符或中括号操作符来访问JSON对象的嵌套属性。

下面是一个嵌套的JSON对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // "secrets"
ourStorage.desk.drawer; // "stapler"
1
2
3
4
5
6
7
8
9
10
11
12
13
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};

var gloveBoxContents = myStorage.car.inside["glove box"]; // Change this line

Accessing Nested Arrays

正如我们在前面的例子所见,JSON对象可以嵌套对象和数组。与访问嵌套对象一样,用中括号操作符同样可以访问嵌套数组。

下面是如何访问嵌套数组的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];

var secondTree = myPlants[1].list[1];

Record Collection

右边有一个JSON对象,代表着你的专辑集。每一张专辑由一个唯一的id标识,并具有多种属性。但并非所有的专辑都有完整的信息。

写一个函数,它有个三个参数,idpropvalue

如果 value !='' 而且prop != 'tracks'collectionCopy[id][prop]=value;

如果 value !='' 而且prop == 'tracks'collectionCopy[id][prop].push(value);

如果 value == ''delete collectionCopy[id][prop];

记住:函数返回的永远是整个对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 初始化变量
var collection = {
2548: {
album: "Slippery When Wet",
artist: "Bon Jovi",
tracks: [
"Let It Rock",
"You Give Love a Bad Name"
]
},

2468: {
album: "1999",
artist: "Prince",
tracks: [
"1999",
"Little Red Corvette"
]
},

1245: {
artist: "Robert Palmer",
tracks: [ ]
},

5439: {
album: "ABBA Gold"
}
};
// 深拷贝 collection,用于测试
var collectionCopy = JSON.parse(JSON.stringify(collection));

// 请只修改这条注释以下的代码
function update(id, prop, value) {

if (collectionCopy[id].hasOwnProperty(prop) !== true){
    collectionCopy[id][prop] = [];
  }  
  if (value === ""){
    delete collectionCopy[id][prop];
  }
  else{
    if (prop === "tracks"){
    collectionCopy[id].tracks.push(value);
    }
    else{
      collectionCopy[id][prop] = value;
    }
  }
return collection;
}

// 你可以修改这一行来测试你的代码
update(5439, "artist", "ABBA");

Iterate with JavaScript While Loops

ou can run the same code multiple times by using a loop.

The first type of loop we will learn is called a “while“ loop because it runs “while” a specified condition is true and stops once that condition is no longer true.

1
2
3
4
5
6
var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}

Iterate with JavaScript For Loops

一个条件语句只能执行一次代码,而一个循环语句可以多次执行代码。

JavaScript 中最常见的循环就是“for循环”。

for循环中的三个表达式用分号隔开:

1
for ([初始化]; [条件判断]; [计数器])

初始化语句只会在执行循环开始之前执行一次。它通常用于定义和设置你的循环变量。

条件判断语句会在每一轮循环的开始执行,只要条件判断为 true 就会继续执行循环。当条件为 false的时候,循环将停止执行。这意味着,如果条件在一开始就为 false,这个循环将不会执行。

计数器是在每一轮循环结束时执行,通常用于递增或递减。

在下面的例子中,先初始化i = 0,条件 i < 5 为真,进入第一次循环,执行大括号里的代码,第一次循环结束。递增i的值,条件判断,就这样依次执行下去,直到条件判断为假,整个循环结束。

var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}

最终 ourArray 的值为 [0,1,2,3,4].

Iterate Odd Numbers With a For Loop

for循环可以按照我们指定的顺序来迭代,通过更改我们的 计数器,我们可以按照偶数顺序来迭代。

初始化 i = 0,当 i < 10 的时候继续循环。

i += 2i 每次循环之后增加2。

var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}

循环结束后,ourArray 的值为 [0,2,4,6,8]

改变 计数器,这样我们可以用奇数来数。

1
2
3
4
5
6
7
8
9
10
11
12
13
var ourArray = [];

for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}

var myArray = [];

for (var i = 0; i < 10; i++) {
if(i%2 == 1){
myArray.push(i);
}
}

Count Backwards With a For Loop

for循环也可以逆向迭代,只要我们定义好合适的条件。

为了能够从后往前两两倒数,我们需要改变我们的 初始化条件判断计数器

我们让 i = 10,并且当 i > 0 的时候才继续循环。我们使用 i-=2 来让 i 每次循环递减 2。

var ourArray = [];
for (var i=10; i > 0; i-=2) {
ourArray.push(i);
}

循环结束后,ourArray 的值为 [10,8,6,4,2]

让我们改变 初始化计数器,这样我们就可以按照奇数从后往前两两倒着数。

1
2
3
4
5
6
7
8
9
10
11
var ourArray = [];

for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}

var myArray = [];

for (var i = 9; i > 0; i-=2){
myArray.push(i)
}

Iterate Through an Array with a For Loop

迭代输出一个数组的每个元素是 JavaScript 中的常见需求, for 循环可以做到这一点。

下面的代码将输出数组 arr 的每个元素到控制台:

1
2
3
4
var arr = [10,9,8,7,6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

记住数组的索引从零开始的,这意味着数组的最后一个元素的下标是:数组的长度 - 1。我们这个循环的 条件 是 i < arr.length,当 i 的值为 长度-1 的时候循环就停止了。

1
2
3
4
5
6
7
8
9
10
11
12
13
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;

for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}

var myArr = [ 2, 3, 4, 5, 6];
var total = 0;

for (var x = 0; x < myArr.length; x++) {
total += myArr[x];
}

Nesting For Loops

如果你有一个二维数组,可以使用相同的逻辑,先遍历外面的数组,再遍历里面的子数组。下面是一个例子:

1
2
3
4
5
6
7
8
var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}

一次输出 arr 中的每个子元素。提示,对于内部循环,我们可以通过 arr[i].length 来获得子数组的长度,因为 arr[i] 的本身就是一个数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for(var i=0; i < arr.length; i++){
for (var j=0; j < arr[i].length; j++){
product = product * arr[i][j];
}
}

// Only change code above this line
return product;
}

// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);

Iterate with JavaScript Do…While Loops

You can run the same code multiple times by using a loop.

The next type of loop you will learn is called a “do...while“ loop because it first will “do“ one pass of the code inside the loop no matter what, and then it runs “while“ a specified condition is true and stops once that condition is no longer true. Let’s look at an example.

1
2
3
4
5
6
var ourArray = [];
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);

This behaves just as you would expect with any other type of loop, and the resulting array will look like [0, 1, 2, 3, 4]. However, what makes the do...whiledifferent from other loops is how it behaves when the condition fails on the first check. Let’s see this in action.

Here is a regular while loop that will run the code in the loop as long as i < 5.

1
2
3
4
5
6
var ourArray = []; 
var i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}

Notice that we initialize the value of ito be 5. When we execute the next line, we notice that iis not less than 5. So we do not execute the code inside the loop. The result is that ourArraywill end up with nothing added to it, so it will still look like this []when all the code in the example above finishes running.

Now, take a look at a do...whileloop.

1
2
3
4
5
6
var ourArray = []; 
var i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);

In this case, we initialize the value of ias 5, just like we did with the while loop. When we get to the next line, there is no check for the value of i, so we go to the code inside the curly braces and execute it. We will add one element to the array and increment ibefore we get to the condition check. Then, when we get to checking if i < 5see that iis now 6, which fails the conditional check. So we exit the loop and are done. At the end of the above example, the value of ourArrayis [5].

Essentially, a do...whileloop ensures that the code inside the loop will run at least once.

Let’s try getting a do...whileloop to work by pushing values to an array.


Change the whileloop in the code to a do...whileloop so that the loop will push the number 10 to myArray, and iwill be equal to 11when your code finishes running.

1
2
3
4
5
6
7
8
9
10
11
12
13
// Setup
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while (i < 5)
// Only change code below this line.

while (i < 5) {
myArray.push(i);
i++;
}

Profile Lookup

我们有一个对象数组,里面存储着通讯录。

函数 lookUp 有两个预定义参数:firstName值和prop属性 。

函数将会检查通讯录中是否存在一个与传入的 firstName 相同的联系人。如果存在,那么还需要检查对应的联系人中是否存在 prop属性。

如果它们都存在,函数返回prop属性对应的值。

如果firstName 值不存在,返回 "No such contact"

如果prop 属性不存在,返回 "No such property"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["JavaScript", "Gaming", "Foxes"]
}
];


function lookUpProfile(firstName, prop){
// Only change code below this line
for( var i = 0; i < contacts.length; i++ ){
if( firstName == contacts[i].firstName ) {
if( contacts[i].hasOwnProperty( prop ) ) {
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

Generate Random Fractions with JavaScript

计算机的行为只有两种:确定性和随机性。当你一步步地闯关来到这里就是确定行为,当你随意点了个链接就来到这里就是随机行为。

而随机数最适合用来创建这种随机行为。

Math.random()用来生成一个在0(包括0)到1(不包括1)之间的随机小数,因此Math.random()可能返回0但绝不会返回1。

提示
随后的函数都会在return执行前调用,所以我们可以直接返回Math.random()的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function randomFraction() {

// Only change code below this line.

var result = 0;

while (result === 0) {
result = Math.random();
}

return result;

// Only change code above this line.
}

Generate Random Whole Numbers with JavaScript

生成随机小数很棒,但随机数更有用的地方在于生成随机整数。

  1. Math.random() 生成一个随机小数。
  2. 把这个随机小数乘以 20
  3. Math.floor() 向下取整 获得它最近的整数。

记住 Math.random() 永远不会返回 1。同时因为我们是在用 Math.floor() 向下取整,所以最终我们获得的结果不可能有 20。这确保了我们获得了一个在0到19之间的整数。

把操作连缀起来,代码类似于下面:

1
Math.floor(Math.random() * 20);

我们先调用 Math.random(),把它的结果乘以20,然后把上一步的结果传给 Math.floor(),最终通过向下取整获得最近的整数。

任务

生成一个 09之间的随机整数。

1
2
3
4
5
6
7
8
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);

function randomWholeNum() {

// Only change code below this line.

return Math.floor(Math.random() * 10);
}

Generate Random Whole Numbers within a Range

我们之前生成的随机数是在0到某个数之间,现在我们要生成的随机数是在两个指定的数之间。

我们需要定义一个最小值和一个最大值。

下面是我们将要使用的方法,仔细看看并尝试理解这行代码到底在干嘛:

1
Math.floor(Math.random() * (max - min + 1)) + min

任务

创建一个叫randomRange的函数,参数为myMin和myMax,返回一个在myMin(包括myMin)和myMax(包括myMax)之间的随机数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function ourRandomRange(ourMin, ourMax) {

return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}

ourRandomRange(1, 9);

// Only change code below this line.

function randomRange(myMin, myMax) {

return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;

}

var myRandom = randomRange(5, 15);

console.log(myRandom);

// Change these values to test your function
var myRandom = randomRange(5, 15);

Use the parseInt Function

The parseInt()function parses a string and returns an integer. Here’s an example:

1
var a = parseInt("007");

The above function converts the string “007” to an integer 7. If the first character in the string can’t be converted into a number, then it returns NaN.


Use parseInt()in the convertToIntegerfunction so it converts the input string strinto an integer, and returns it.

1
2
3
4
5
function convertToInteger(str){
return parseInt(str);
}

convertToInteger("56");

Use the parseInt Function with a Radix

The parseInt()function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36.

The function call looks like:

1
parseInt(string, radix);

And here’s an example:

1
var a = parseInt("11", 2);

The radix variable says that “11” is in the binary system, or base 2. This example converts the string “11” to an integer 3.


Use parseInt()in the convertToIntegerfunction so it converts a binary number to an integer and returns it.

1
2
3
4
5
6
function convertToInteger(str) {
var radix = 2;
return parseInt(str, radix);
}

convertToInteger("10011");

Use the Conditional (Ternary) Operator

The conditional operator, also called the ternary operator, can be used as a one line if-else expression.

The syntax is:

1
condition ? statement-if-true : statement-if-false;

The following function uses an if-else statement to check a condition:

1
2
3
4
5
6
7
8
function findGreater(a, b) {
if(a > b) {
return "a is greater";
}
else {
return "b is greater";
}
}

This can be re-written using the conditional operator:

1
2
3
function findGreater(a, b) {
return a > b ? "a is greater" : "b is greater";
}

练习:

Use the conditional operatorin the checkEqualfunction to check if two numbers are equal or not. The function should return either true or false.

1
2
3
4
5
function checkEqual(a, b) {
return (a == b ? true : false );
}

checkEqual(1, 2);

Use Multiple Conditional (Ternary) Operators

In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions.

The following function uses if, else if, and else statements to check multiple conditions:

1
2
3
4
5
6
7
8
9
10
11
function findGreaterOrEqual(a, b) {
if(a === b) {
return "a and b are equal";
}
else if(a > b) {
return "a is greater";
}
else {
return "b is greater";
}
}

The above function can be re-written using multiple conditional operators:

1
2
3
function findGreaterOrEqual(a, b) {
return (a === b) ? "a and b are equal" : (a > b) ? "a is greater" : "b is greater";
}

练习:

Use multiple conditional operatorsin the checkSignfunction to check if a number is positive, negative or zero.

1
2
3
4
5
function checkSign(num) {
return (num > 0) ? 'positive' : (num < 0) ? 'negative' : 'zero';
}

checkSign(10);