第一部分 基础知识
第6章 条件与循环
- 条件有if和else if; if是只判断( )里的条件是否为真,else if是既判断之间if是否为假,再判断( )里的条件是否为真
- if的写法:if(condition // 为真) { //do something }
- if…else的写法:if (condition // 为真) { // do something } else { // do something else }
程序举例25
// Make an order
var lemonChicken = false
var beefWithBlackBean = false
var sweetAndSourPork = true
if (lemonChicken) {
console.log ("Great, I am having Lemon Chicken!")
} else if (beefWithBlackBean) {
console.log ("OK, I am having the breef.")
} else if (sweetAndSourPork) {
console.log ("Fine, I am having the pork.")
} else {
console.log ("OK, I guess I will have rice.")
}
返回值:Fine, I am having the pork.
程序举例26
//Send a greeting
var name = "Winnie"
if(name === "Winnie") {
console.log ("Hello, me.")
} else if (name === "Fanny") {
console.log ("Hello, Fanny. ")
} else if (name === "David"){
console.log ("Hello, David.")
} else {
console.log ("Hello, stranger.")
}
当name = “Winnie”时,返回值:Hello, me.
当name = “Fanny”时,返回值:Hello, Fanny.
当name = “David”时,返回值:Hello, David.
当name = //其他人时,返回值:Hello, stranger.
- while循环在当条件为真时会一直重复执行它的主体
- while循环的写法:while (condition //为真) { do something }
程序举例27
//Count sheep
var i = 0
while (i < 10){
console.log ("I have counted "+i+" sheep!")
i += 1
}
console.log (“Zzzzzzzzz")
返回值:
I have counted 0 sheep!
I have counted 1 sheep!
I have counted 2 sheep!
I have counted 3 sheep!
I have counted 4 sheep!
I have counted 5 sheep!
I have counted 6 sheep!
I have counted 7 sheep!
I have counted 8 sheep!
I have counted 9 sheep!
Zzzzzzzzz
6. for循环的写法:for (setup; condition; increment) { //do something }
程序举例28
//Count sheep with [FOR]
for (i=0;i<10;i+=1){
console.log ("I haved counted "+i+" sheep.")
}
console.log (“ZzzzzzzzZ")
返回值:
I have counted 0 sheep!
I have counted 1 sheep!
I have counted 2 sheep!
I have counted 3 sheep!
I have counted 4 sheep!
I have counted 5 sheep!
I have counted 6 sheep!
I have counted 7 sheep!
I have counted 8 sheep!
I have counted 9 sheep!
ZzzzzzzzZ
程序举例29
//List out all numbers (<10000) multiply with 3
for (i=3; i<10000; i *= 3){
console.log (i)
}
返回值:
3
9
27
81
243
729
2187
6561
程序举例30
//Make a group of awesome animals
var animals = ["Cat", "Fish", "Lemur", "Komodo Dragon"]
awesomeAnimals = []
for (i=0; i< animals.length; i += 1){
awesomeAnimals.push ("Awesome "+animals [i])
}
console.log (awesomeAnimals)
返回值:["Awesome Cat", "Awesome Fish", "Awesome Lemur", "Awesome Komodo Dragon"]