Comment
第1种
1 | //这是注释 |
第2种
1 | /* 这是 |
Variables
JS有7种数据类型:undefined
, null
, boolean
, string
, symbol
, number
, and object
。
定义变量
1 | var 变量名 |
变量名不可以包含空格,也不可以以1个数字开始。
赋值
1 | var a; |
未初始化变量
When JavaScript variables are declared, they have an initial value of
undefined
.If you do a mathematical operation on an
undefined
variable your result will beNaN
which means “Not a Number”.If you concatenate a string with an
undefined
variable, you will get a literal string of"undefined"
.
1 | var a = 5; |
大小写敏感
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 | // Declarations |
递增运算符
1 | i++; |
is the equivalent of
1 | i = i + 1; |
1 | var myVar = 87; |
递减运算符
1 | var myVar = 11; |
十进制数值 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 | var remainder; |
复合赋值运算符
Augmented Addition
1 | var myVar = 1; |
1 | myVar = myVar + 5; |
1 | var a = 3; |
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 | var myStr = "This is the first sentence. "; |
字符串值长度
.length
属性
1 | lastNameLength = lastName.length; |
索引(Bracket Notation)
1 | firstLetterOfLastName = lastName[0]; |
不可改变的字符串
In JavaScript, String
values 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 | function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) |
列表
1 | var sandwich = ["peanut butter", "jelly", "bread"] |
nested array
1 | var ourArray = [["the universe", 42], ["everything", 101010]]; |
Modify Array Data With Indexes
1 | var ourArray = [18,64,99]; |
多维数组
1 | var arr = [ |
push函数
1 | var arr = [1,2,3]; |
pop函数
1 | var threeArr = [1, 4, 6]; |
shift函数
remove first
1 | var ourArray = ["Stimpson", "J", ["cat"]]; |
unshift函数
向数组的开头添加元素
1 | var ourArray = ["Stimpson", "J", "cat"]; |
Reusable Functions
1 | function functionName() { |
Passing Values to Functions with Arguments
1 | function testFun(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 | function functionWithArgs(a, b){ |
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 var
keyword are automatically created in the global
scope. 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 | var myGlobal = 10; |
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 | function myTest() { |
loc
is not defined outside of the function.
在函数外,loc
是未定义的。
1 | function 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 local
variable takes precedence over the global
variable.
一个程序中有可能具有相同名称的 局部 变量 和 全局变量。在这种情况下,局部
变量将会优先于 全局
变量。
In this example:
1 | var someVar = "Hat"; |
The function myFun
will return "Head"
because the local
version of the variable is present.
函数 myFun
将会返回 "Head"
,因为 局部变量
优先级更高。
1 | var outerWear = "T-Shirt"; |
Return a Value from a Function with Return
We can pass values into a function with arguments. You can use a return
statement to send a value back out of a function.
我们可以把数据通过函数的 参数 来传入函数,也可以使用 return
语句把数据从一个函数中传出来。
1 | function plusThree(num) { |
plusThree
takes an argument for num
and returns a value equal to num + 3
.
plusThree
带有一个为 num
的 参数 并且返回(returns)一个等于 num + 3
的值。
1 | function minusSeven(num) { |
Understanding Undefined Value returned from a Function
A function can include the return
statement but it does not have to. In the case that the function doesn’t have a return
statement, when you call it, the function processes the inner code but the returned value is undefined
.
1 | var sum = 0; |
addSum
is a function without a return
statement. The function will change the global sum
variable but the returned value of the function is undefined
Create a function addFive
without any arguments. This function adds 5 to the sum
variable, but its returned value is undefined
.
1 | var sum = 0; |
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 sum
which adds two numbers together, then:
假设我们预先定义的函数 sum
其功能就是将两个数字相加,那么:
1 | ourSum = sum(5, 12); |
will call sum
function, which returns a value of 17
and assigns it to ourSum
variable.
将调用 sum
函数,返回return
了一个数值 17
,然后把它赋值给了 ourSum
变量。
练习:
1 | var changed = 0; |
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 queue
and old items are taken off from the front of the queue
.
Write a function nextInLine
which 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 nextInLine
function should then return the element that was removed.
在计算机科学中 队列(queue)是一个抽象的数据结构,队列中的条目都是有秩序的。新的条目会被加到 队列
的末尾,旧的条目会从 队列
的头部被移出。
写一个函数 queue
,用一个数组arr
和一个数字item
作为参数。数字item
添加到数组的结尾,然后移出数组的第一个元素,最后队列函数应该返回被删除的元素。
1 | function nextInLine(arr, item) { |
Boolean
Another data type is the Boolean. Booleans
may only be one of two values: true
or false
. They are basically little on-off switches, where true
is “on” and false
is “off.” These two states are mutually exclusive.
另一种数据类型是布尔(Boolean)。布尔
值要么是true
要么是false
。它非常像电路开关, true
是“开”,false
是“关”。这两种状态是互斥的。
注意Boolean
值绝不会写作被引号包裹起来的形式。字符串
的 "true"
和 "false"
不是 布尔值
,在 JavaScript 中也没有特殊含义。
NoteBoolean
values are never written with quotes. The strings`
“true”and
“false”are not
Boolean`and have no special meaning in JavaScript.
练习:
1 | function welcomeToBooleans() { |
If Statements
If
statements are used to make decisions in code. The keyword if
tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as Boolean
conditions and they may only be true
or 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 | if (condition is true) { |
1 | function test (myCondition) { |
When test
is called with a value of true
, the if
statement evaluates myCondition
to see if it is true
or not. Since it is true
, the function returns "It was true"
. When we call test
with a value of false
, myCondition
is not true
and the statement in the curly braces is not executed and the function returns "It was false"
.
当 test
被调用,并且传递进来的参数值为 true
,if
语句会计算 myCondition
的结果,看它是真还是假。如果条件为 true
,函数会返回 "It was true"
。当 test
被调用,并且传递进来的参数值为 false
,myCondition
不 为 true
,并且不执行大括号后面的语句,函数返回 "It was false"
。
练习:
Create an if
statement inside the function to return "Yes, that was true"
if the parameter wasThatTrue
is true
and return "No, that was false"
otherwise.
1 | function ourTrueOrFalse(isItTrue) { |
Equality Operator 相等运算符
here are many Comparison Operators in JavaScript. All of these operators return a boolean true
or false
value.
The most basic operator is the equality operator ==
. The equality operator compares two values and returns true
if they’re equivalent or false
if 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 中,有很多 相互比较的操作。所有这些操作符都返回一个 true
或 false
值。
最基本的运算符是相等运算符:==
。相等运算符比较两个值,如果它们是同等,返回 true
,如果它们不等,返回 false
。值得注意的是相等运算符不同于赋值运算符(=
),赋值运算符是把等号右边的值赋给左边的变量。
1 | function equalityTest(myVal) { |
If myVal
is 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, numbers
and 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 | 1 == 1 // true |
练习:
1 | function myTest(val) { |
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 | 3 === 3 // true |
In the second example, 3
is a Number
type and '3'
is a String
type.
练习:
1 | function testStrict(val) { |
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 | 3 == '3' // returns true because JavaScript performs type conversion from string to number |
Note
In JavaScript, you can determine the type of a variable or a value with the typeof
operator, as follows:
1 | typeof 3 // returns 'number' |
练习:
The compareEquality
function 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 | function compareEquality(a, b) { |
Inequality Operator 不相等运算符
The inequality operator (!=
) is the opposite of the equality operator. It means “Not Equal” and returns false
where equality would return true
and vice versa. Like the equality operator, the inequality operator will convert data types of values while comparing.
不相等运算符(!=
)与相等运算符是相反的。这意味着不相等运算符中,如果“不为真”并且返回 false
的地方,在相等运算符中会返回true
,反之亦然。与相等运算符类似,不相等运算符在比较的时候也会转换值的数据类型。
1 | 1 != 2 // true |
1 | function testNotEqual(val) { |
Strict Inequality Operator 严格相等运算符
The strict inequality operator (!==
) is the logical opposite of the strict equality operator. It means “Strictly Not Equal” and returns false
where strict equality would return true
and vice versa. Strict inequality will not convert data types.
严格相等运算符(===
)是相对于相等操作符(==
)的一种操作符。与相等操作符不同的是,它会同时比较元素的值和 数据类型
。
1 | 3 === 3 // true |
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 | 5 > 3 // true |
the Greater Than Or Equal To Operator 大于等于运算符
The greater than or equal to
operator (>=
) 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 to
operator will convert data types while comparing.
使用 大于等于
运算符(>=
)来比较两个数字的大小。如果大于等于运算符左边的数字比右边的数字大或者相等,它会返回 true
。否则,它会返回 false
。
与相等运算符相似,大于等于
运算符在比较的时候会转换值的数据类型。
1 | 6 >= 6 // true |
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 < 5 // true |
the Less Than Or Equal To Operator 小于等于运算符
The less than or equal to
operator (<=
) 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 to
converts data types.
1 | 4 <= 5 // true |
the Logical And Operator
Sometimes you will need to test more than one thing at a time. The logical and operator (&&
) returns true
if 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 | if (num > 5) { |
will only return “Yes” if num
is greater than 5
and less than 10
. The same logic can be written as:
只有当 num
的值在6和9之间(包括6和9)才会返回 “Yes”。相同的逻辑可被写为:
1 | if (num > 5 && num < 10) { |
the Logical Or Operator
The logical or operator (||
) returns true
if 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 | if (num > 10) { |
will return “Yes” only if num
is between 5
and 10
(5 and 10 included). The same logic can be written as:
只有当num
大于等于5或小于等于10时,函数返回”Yes”。相同的逻辑可以简写成:
1 | if (num > 10 || num < 5) { |
练习:
1 | function testLogicalOr(val) { |
Introducing Else Statements
When a condition for an if
statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an else
statement, an alternate block of code can be executed.
当if
语句的条件为真,大括号里的代码执行,那如果条件为假呢?
正常情况下什么也不会发生。
写一个else
语句,当条件为假时执行相应的代码。
1 | if (num > 10) { |
1 | function testElse(val) { |
Else If Statements
If you have multiple conditions that need to be addressed, you can chain if
statements together with else if
statements.
如果你有多个条件语句,你可以通过else if
语句把 if
语句链起来。
1 | if (num > 15) { |
1 | function testElseIf(val) { |
Logical Order in If Else Statements
Order is important in if
, else if
statements.
The function is executed from top to bottom so you will want to be careful of what statement comes first.
if
、else if
语句中代码的执行顺序是很重要的。
在条件判断语句中,代码的执行顺序是从上到下,所以你需要考虑清楚先执行哪一句,后执行哪一句。
Take these two functions as an example.
Here’s the first:
1 | function foo(x) { |
And the second just switches the order of the statements:
第二个例子更改了代码的执行顺序:
1 | function bar(x) { |
While these two functions look nearly identical if we pass a number to both we get different outputs.
这两个函数看起来几乎一模一样,我们传一个值进去看看它们有什么区别。
1 | foo(0) // "Less than one" |
练习:
1 | function orderMyLogic(val) { |
Chaining If Else Statements
if/else
statements can be chained together for complex logic. Here is pseudocode of multiple chained if
/ else if
statements:
if/else
语句串联在一起可以实现复杂的逻辑,这是多个if/else if
语句串联在一起的伪代码:
1 | if (condition1) { |
Write chained if
/else if
statements 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 | function testSize(num) { |
Golf Code
In the game of golf each hole has a par
meaning the average number of strokes
a 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 par
your strokes
are, there is a different nickname.
Your function will be passed par
and strokes
arguments. 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!” |
par
and strokes
will always be numeric and positive. We have added an array of all the names for your convenience.
par
和 strokes
必须是数字而且是正数。
1 | var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"]; |
Switch Statements
If you have many options to choose from, use a switch
statement. A switch
statement tests a value and can have many case
statements which define various possible values. Statements are executed from the first matched case
value until a break
is encountered.
如果你有非常多的选项需要选择,可以使用switch语句。根据不同的参数值会匹配上不同的case分支,语句会从第一个匹配的case分支开始执行,直到碰到break就结束。
Here is a pseudocode example:
1 | switch(num) { |
case
values are tested with strict equality (===
). The break
tells JavaScript to stop executing statements. If the break
is omitted, the next statement will be executed.
测试case
值使用严格相等运算符进行比较,break关键字告诉javascript停止执行语句。如果没有break关键字,下一个语句会继续执行。
Write a switch statement which tests val
and sets answer
for the following conditions:
写一个测试 val
的switch语句,并且根据下面的条件来设置不同的answer
:
1
- “alpha”2
- “beta”3
- “gamma”4
- “delta”
1 | function caseInSwitch(val) { |
Adding a Default Option in Switch Statements
In a switch
statement you may not be able to specify all possible values as case
statements. Instead, you can add the default
statement which will be executed if no matching case
statements are found. Think of it like the final else
statement in an if/else
chain.
在switch
语句中你可能无法用case来指定所有情况,这时你可以添加default语句。当再也找不到case匹配的时候default语句会执行,非常类似于if/else组合中的else语句。
A default
statement should be the last case.
1 | switch (num) { |
Write a switch statement to set answer
for the following conditions:"a"
- “apple”"b"
- “bird”"c"
- “cat”default
- “stuff”
1 | function myTest(val) { |
Multiple Identical Options in Switch Statements
If the break
statement is omitted from a switch
statement’s case
, the following case
statement(s) are executed until a break
is encountered. If you have multiple inputs with the same output, you can represent them in a switch
statement like this:
如果switch
语句中的case
分支的break
语句漏掉了,后面的 case
语句会一直执行直到遇到break
。如果你有多个输入值和输出值一样,可以试试下面的switch
语句:
1 | switch(val) { |
Cases for 1, 2, and 3 will all produce the same result.
分支1、2、3将会产生相同的输出结果。
Write a switch statement to set answer
for the following ranges:1-3
- “Low”4-6
- “Mid”7-9
- “High”
Note
You will need to have a case
statement for each number in the range.
1 | function sequentialSizes(val) { |
Replacing If Else Chains with Switch
If you have many options to choose from, a switch
statement can be easier to write than many chained if
/else if
statements. The following:
1 | if (val === 1) { |
can be replaced with:
1 | switch(val) { |
练习:
1 | function chainToSwitch(val) { |
Returning Boolean Values from Functions
You may recall from Comparison with the Equality Operator that all comparison operators return a boolean true
or false
value.
Sometimes people use an if/else statement to do a comparison, like this:
你可能会回想起Comparison with the Equality Operator ,所有的比较操作符返回的都是一个boolean值,要么是 true
要么是false
。
使用 if/else
语句来做比较然后返回true
或false
已经成为大家的共识:
1 | function isEqual(a,b) { |
But there’s a better way to do this. Since ===
returns true
or false
, we can return the result of the comparison:
因为===
总是返回 true
或 false
,所以我们可以直接返回比较的结果:
1 | function isEqual(a,b) { |
练习:
1 | function isLess(a, b) { |
Return Early Pattern for Functions
When a return
statement is reached, the execution of the current function stops and control returns to the calling location.
当代码执行到return语句时,函数返回一个结果就结束运行了,return后面的语句根本不会执行。
1 | function myFun() { |
The above outputs “Hello” to the console, returns “World”, but "byebye"
is never output, because the function exits at the return
statement.
上面的代码输出”Hello”到控制台、返回 “World”,但没有输出"byebye"
,因为函数遇到return语句就退出了。
Modify the function abTest
so that if a
or b
are less than 0
the function will immediately exit with a value of undefined
.
修改函数abTest
当a
或b
小于0时,函数立即返回一个undefined
并退出。
Hint
Remember that undefined
is a keyword, not a string.
1 | function abTest(a, b) { |
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 card
parameter, which can be a number or a string, and increment or decrement the global count
variable according to the card’s value (see table). The function will then return a string with the current count and the string Bet
if the count is positive, or Hold
if the count is zero or negative. The current count and the player’s decision (Bet
or 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 count
to 0 when value is 7, 8, or 9.
Do NOT return an array.
Do NOT include quotes (single or double) in the output.
1 | var count = 0; |
创建JS对象
对象和数组很相似,数组是通过索引来访问和修改数据,对象是通过属性来访问和修改数据的。
1 | var cat = { |
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 | var anotherObject = { |
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
1 | var ourDog = { |
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 | var myObj = { |
1 | var testObj = { |
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 | var myObj = { |
Note that property names with spaces in them must be in quotes (single or double).
1 | var testObj = { |
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 | var dogs = { |
Another way you can use this concept is when the property’s name is collected dynamically during the program execution, as follows:
1 | var someObj = { |
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 | var testObj = { |
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 | var ourDog = { |
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 | // Example |
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 switch
statement or an if/else
chain. 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 | var alpha = { |
1 | function phoneticLookup(val) { |
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 true
or false
if the property is found or not.
有时检查一个对象属性是否存在是非常有用的,我们可以用.hasOwnProperty(propname)
方法来检查对象是否有该属性。如果有返回true
,反之返回 false
。
1 | var myObj = { |
1 | var myObj = { |
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 | var ourMusic = [ |
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 JSON
is a related data interchange format used to store data.
1 | { |
Note
You will need to place a comma after every object in the array, unless it is the last object in the array.
1 | var myMusic = [ |
Accessing Nested Objects
通过串联起来的点操作符或中括号操作符来访问JSON对象的嵌套属性。
下面是一个嵌套的JSON对象:
1 | var ourStorage = { |
1 | var myStorage = { |
Accessing Nested Arrays
正如我们在前面的例子所见,JSON对象可以嵌套对象和数组。与访问嵌套对象一样,用中括号操作符同样可以访问嵌套数组。
下面是如何访问嵌套数组的例子:
1 | var ourPets = [ |
1 | var myPlants = [ |
Record Collection
右边有一个JSON对象,代表着你的专辑集。每一张专辑由一个唯一的id标识,并具有多种属性。但并非所有的专辑都有完整的信息。
写一个函数,它有个三个参数,id
、prop
、 value
。
如果 value !=''
而且prop != 'tracks'
,collectionCopy[id][prop]=value;
。
如果 value !=''
而且prop == 'tracks'
,collectionCopy[id][prop].push(value);
。
如果 value == ''
,delete collectionCopy[id][prop];
。
记住:函数返回的永远是整个对象。
1 | // 初始化变量 |
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 | var ourArray = []; |
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 += 2
让 i
每次循环之后增加2。
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
循环结束后,ourArray
的值为 [0,2,4,6,8]
。
改变 计数器
,这样我们可以用奇数来数。
1 | var ourArray = []; |
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 | var ourArray = []; |
Iterate Through an Array with a For Loop
迭代输出一个数组的每个元素是 JavaScript 中的常见需求, for
循环可以做到这一点。
下面的代码将输出数组 arr
的每个元素到控制台:
1 | var arr = [10,9,8,7,6]; |
记住数组的索引从零开始的,这意味着数组的最后一个元素的下标是:数组的长度 - 1。我们这个循环的 条件 是 i < arr.length
,当 i
的值为 长度-1 的时候循环就停止了。
1 | var ourArr = [ 9, 10, 11, 12]; |
Nesting For Loops
如果你有一个二维数组,可以使用相同的逻辑,先遍历外面的数组,再遍历里面的子数组。下面是一个例子:
1 | var arr = [ |
一次输出 arr
中的每个子元素。提示,对于内部循环,我们可以通过 arr[i]
的 .length
来获得子数组的长度,因为 arr[i]
的本身就是一个数组。
1 | function multiplyAll(arr) { |
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 | var ourArray = []; |
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...while
different 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 | var ourArray = []; |
Notice that we initialize the value of i
to be 5. When we execute the next line, we notice that i
is not less than 5. So we do not execute the code inside the loop. The result is that ourArray
will 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...while
loop.
1 | var ourArray = []; |
In this case, we initialize the value of i
as 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 i
before we get to the condition check. Then, when we get to checking if i < 5
see that i
is 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 ourArray
is [5]
.
Essentially, a do...while
loop ensures that the code inside the loop will run at least once.
Let’s try getting a do...while
loop to work by pushing values to an array.
Change the while
loop in the code to a do...while
loop so that the loop will push the number 10 to myArray
, and i
will be equal to 11
when your code finishes running.
1 | // Setup |
Profile Lookup
我们有一个对象数组,里面存储着通讯录。
函数 lookUp
有两个预定义参数:firstName
值和prop
属性 。
函数将会检查通讯录中是否存在一个与传入的 firstName
相同的联系人。如果存在,那么还需要检查对应的联系人中是否存在 prop
属性。
如果它们都存在,函数返回prop
属性对应的值。
如果firstName
值不存在,返回 "No such contact"
。
如果prop
属性不存在,返回 "No such property"
。
1 | var contacts = [ |
Generate Random Fractions with JavaScript
计算机的行为只有两种:确定性和随机性。当你一步步地闯关来到这里就是确定行为,当你随意点了个链接就来到这里就是随机行为。
而随机数最适合用来创建这种随机行为。
Math.random()
用来生成一个在0(包括0)到1(不包括1)之间的随机小数,因此Math.random()
可能返回0但绝不会返回1。
提示
随后的函数都会在return
执行前调用,所以我们可以直接返回Math.random()
的值。
1 | function randomFraction() { |
Generate Random Whole Numbers with JavaScript
生成随机小数很棒,但随机数更有用的地方在于生成随机整数。
- 用
Math.random()
生成一个随机小数。 - 把这个随机小数乘以
20
。 - 用
Math.floor()
向下取整 获得它最近的整数。
记住 Math.random()
永远不会返回 1
。同时因为我们是在用 Math.floor()
向下取整,所以最终我们获得的结果不可能有 20
。这确保了我们获得了一个在0到19之间的整数。
把操作连缀起来,代码类似于下面:
1 | Math.floor(Math.random() * 20); |
我们先调用 Math.random()
,把它的结果乘以20,然后把上一步的结果传给 Math.floor()
,最终通过向下取整获得最近的整数。
任务
生成一个 0
到 9
之间的随机整数。
1 | var randomNumberBetween0and19 = Math.floor(Math.random() * 20); |
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 | function ourRandomRange(ourMin, ourMax) { |
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 convertToInteger
function so it converts the input string str
into an integer, and returns it.
1 | function convertToInteger(str){ |
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 convertToInteger
function so it converts a binary number to an integer and returns it.
1 | function convertToInteger(str) { |
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 | function findGreater(a, b) { |
This can be re-written using the conditional operator
:
1 | function findGreater(a, b) { |
练习:
Use the conditional operator
in the checkEqual
function to check if two numbers are equal or not. The function should return either true or false.
1 | function checkEqual(a, b) { |
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 | function findGreaterOrEqual(a, b) { |
The above function can be re-written using multiple conditional operators
:
1 | function findGreaterOrEqual(a, b) { |
练习:
Use multiple conditional operators
in the checkSign
function to check if a number is positive, negative or zero.
1 | function checkSign(num) { |