1.循环语句:
for():
Eg:
for (var index=0; index < continents.length; index++)
for...in... :
Eg:
for (var index in continents)
for...of... :
Eg:
for (var continent of continents)
无限循环:
for ( ; ; ) {
alert("Welcome!");
}
2.控制循环:break 、continue:
break:完全停止循环。
continue:停止本次循环,继续下一次循环。
3.more on arrays:(函数)
1>array.sort() sorts the elements in array:
var pets = ["Dog", "Cat", "Rabbit", "Hamster"];
pets.sort();
// Now pets is ["Cat", "Dog", "Hamster", "Rabbit"]
2>array.reverse() reverses array
The first element becomes the last;
The last element becomes the first
var pets = ["Dog", "Cat", "Rabbit", "Hamster"];
pets.reverse();
// pets is ["Hamster", "Rabbit", "Cat", "Dog"]
3>Use array.indexOf(target) to find the index of
the first occurence of target in array:
If target is not in array, indexOf() will return -1
var pets = ["Dog", "Cat", "Rabbit", "Hamster"];
alert(pets.indexOf("Rabbit")); // This shows 2
If target is not in array, indexOf() will return -1
4>Pass a second value to indexOf()
to control where to start the search
array.indexOf(target, startPosition)
5>Use array.lastIndexOf(target) to find target in array,
starting from the last element in array:
var pets = ["Rabbit", "Dog", "Cat",
"Rabbit", "Hamster"];
alert(pets.lastIndexOf("Rabbit")); // This shows 3
6>Extract part of an array by array.slice(startPosition):
var pets = ["Dog", "Cat", "Rabbit", "Hamster"];
var result = pets.slice(1);
// result is ["Cat", "Rabbit", "Hamster"]
7>You can also set where to stop, by
array.slice(startPosition, endPosition):
var pets = ["Dog", "Cat", "Rabbit", "Hamster"];
var result = pets.slice(1, 3);
// result is ["Cat", "Rabbit"]
8>remove elements from arrays:
array.splice(position, quantity);
var pets = ["Dog", "Cat", "Rabbit", "Hamster"];
var result = pets.splice(1, 1);
// Now pets is ["Dog", "Rabbit", "Hamster"]
// and result is ["Cat"]
**splice() returns the removed element(s)
9>add element(s):
array.splice(position, 0, element):
var pets = ["Dog", "Cat", "Hamster"];
var result = pets.splice(2, 0, "Rabbit");
// Now pets is ["Dog", "Cat", "Rabbit", "Hamster"]
// and result is []
10>replace element(s) :
array.splice(position, quantity, element(s)):
var pets = ["Dog", "Cat", "Hamster"];
var result = pets.splice(1, 1, "Rabbit", "Fish");
// Now pets is ["Dog", "Rabbit", "Fish", "Hamster"]
// and result is ["Cat"].
4.高级的数组操作函数:
1>遍历数组:
可以用循环for,while;
也可用内置函数foreach(function).
Eg:
var pets = ["Dog", "Cat", "Rabbit"];
pets.forEach(alert);
// This shows 3 separate alerts
2>map(function):
<!doctype html>
<html>
<body>
<script>
var square = function(el) { return el * el; }
var numbers = [1, 2, 3, 4, 5];
var results = numbers.map(square);
alert(results); // This shows [1,4,9,16,25];
</script>
</body>
</html>