循环语句
·
Yin灏
/*
for(...) {}
for(... of ...) {}
for(... in ...) {}
*/
let fruits = ['apple', 'blueberry', 'cherry', 'durian', 'Fig', 'Grape', 'Hwa', 'Kiwi', 'Lichee', 'Mango', 'Nucleus'];
let message = '';
for (let i = 1; i < fruits.length; i++) {
message += `(${i}) ${fruits[i - 1]} `;
}
console.log(message); // (1) apple (2) blueberry (3) cherry (4) durian (5) Fig (6) Grape (7) Hwa (8) Kiwi (9) Lichee (10) Mango
console.log('')
message = '';
for(let value of fruits) {
message += `${value} `
}
console.log(message); // apple blueberry cherry durian Fig Grape Hwa Kiwi Lichee Mango Nucleus
let product = { id: 5685, name: 'Tablet PC', color: 'Gold', Price: '1200', OS: 'Android' }
message = '';
for(let str in product) {
message += `${str} `;
}
console.log(message); // id name color Price OS
for...of...
语句必须配合可迭代(iterable
)的对象实例,才可迭代其各个属性。
let a01 = [520, 530, 1314, 2013, 2014, 2591.8];
let sum = 0;
for (let num of a01) {
sum += num;
console.log(`current number = ${num}`)
}
/*
current number = 520
current number = 530
current number = 1314
current number = 2013
current number = 2014
current number = 2591.8
*/
console.log('')
let greeting = 'Hello, world, Solar System, Galaxy.';
for (let c of greeting) {
console.log(c); // 遍历字符串的每一个字符
}
console.log('')
function display(...args) {
for (let arg of args) {
console.log(arg)
}
console.log('');
for (let arg of arguments) {
console.log(arg)
}
}
display('what', 'when', 'where', 'which', 'who')
// 生成器函数
function* gen01() {
let top_value = parseInt(30 * Math.random());
for (let i = 1; i < top_value; i += 3) {
yield i; // 遇到 yield,函数将暂时终止; yield 有 return 的功能,向外返回值
}
}
let gen02 = {
*[Symbol.iterator]() {
let top_value = parseInt(30 * Math.random());
for (let i = 1; i < top_value; i += 3) {
yield i;
}
}
}
for (let num of gen01()) {
console.log(num)
}
console.log('')
for (let num of gen02) {
console.log(num)
}
let number_array = [...gen01()];
console.log(number_array); // [1, 4, 7, 10, 13, 16, 19]
console.log('')
class Planets {
* solar_system() {
let planet_list = ['水星', '金星', '地球', '火星', '木星', '土星', '天王星'];
for(let planet of planet_list) {
yield planet;
}
}
}
p01 = new Planets();
let a_copy = [...p01.solar_system()];
console.log(a_copy); // ["水星", "金星", "地球", "火星", "木星", "土星", "天王星"]
whie
相关语句:
/*
while(...) {
...
}
do {
...
} while(...) { ... }
*/
let fruits = ['apple', 'blueberry', 'cherry', 'durian', 'Fig', 'Grape', 'Haw', 'Kiwi'];
let product = {
id: 5685,
name: 'Tablet PC',
color: 'Gold',
Price: '1200',
OS: 'Android'
};
let message = '', count = 1;
while(count < fruits.length + 1) {
message += `(${count}) ${fruits[count - 1]} `;
count++;
}
console.log(message); // (1) apple (2) blueberry (3) cherry (4) durian (5) Fig (6) Grape (7) Haw (8) Kiwi
console.log('');
message = '', count = 1;
do {
message += `(${count}) ${fruits[count-1]} `;
count ++;
} while(count < fruits.length + 1);
console.log(message); // (1) apple (2) blueberry (3) cherry (4) durian (5) Fig (6) Grape (7) Haw (8) Kiwi