返回
通过代码体会for-in、while、do-while及函数基础
前端
2023-11-19 23:14:31
1. for-in 循环
1.1 概述
for-in循环用于遍历对象的可枚举属性。它将对象的可枚举属性一一列举出来,并依次对每个属性的值进行操作。
1.2 语法
for (variable in object) {
// 执行操作
}
1.3 示例
const person = {
name: 'John',
age: 30,
city: 'New York'
};
for (const key in person) {
console.log(key, person[key]);
}
输出结果:
name John
age 30
city New York
2. while 循环
2.1 概述
while循环是一种循环语句,它会在满足条件的情况下反复执行代码块。
2.2 语法
while (condition) {
// 执行操作
}
2.3 示例
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
输出结果:
0
1
2
3
4
5
6
7
8
9
3. do-while 循环
3.1 概述
do-while循环是一种循环语句,它会先执行代码块,然后再检查条件。如果条件为真,则继续执行代码块;如果条件为假,则停止循环。
3.2 语法
do {
// 执行操作
} while (condition);
3.3 示例
let i = 0;
do {
console.log(i);
i++;
} while (i < 10);
输出结果:
0
1
2
3
4
5
6
7
8
9
4. 函数
4.1 概述
函数是javascript中代码的封装,它可以接受参数,并返回结果。函数可以被多次调用,并且可以被其他函数调用。
4.2 语法
function functionName(parameters) {
// 函数体
}
4.3 示例
function sum(a, b) {
return a + b;
}
const result = sum(1, 2);
console.log(result); // 输出 3