提供十个JavaScript的算例,包含if,for,while等语句
时间: 2024-10-09 17:14:37 浏览: 29
当然可以,以下是十个简单的JavaScript示例,涵盖if、for、while等常见语句:
1. **基础if语句**:
```javascript
let num = 5;
if (num > 0) {
console.log('数是正的');
}
```
2. **基本for循环**:
```javascript
for (let i = 0; i < 5; i++) {
console.log(i);
}
```
3. **计数到特定数值的for循环**:
```javascript
for (let j = 1; j <= 10; j *= 2) { // 这里会打印出2的幂
console.log(j);
}
```
4. **while循环计算斐波那契数列**:
```javascript
let a = 0, b = 1;
let fib = 0;
while (fib < 10) {
console.log(fib);
[a, b] = [b, a + b];
fib++;
}
```
5. **数组元素查找(if嵌套)**:
```javascript
const array = [1, 2, 3, 4, 5];
if (array.includes(3)) {
console.log('找到了数字3');
}
```
6. **条件判断数组长度**:
```javascript
let arr = [];
if (arr.length === 0) {
console.log('数组为空');
}
```
7. **使用switch语句**:
```javascript
let day = 'Monday';
switch (day) {
case 'Sunday':
console.log('休息日');
break;
default:
console.log('工作日');
}
```
8. **遍历对象属性**:
```javascript
let person = {name: 'John', age: 30};
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ': ' + person[key]);
}
}
```
9. **递归计算阶乘**:
```javascript
function factorial(n) {
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
console.log(factorial(5));
}
```
10. **异步操作示例(Promise)**:
```javascript
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise resolved'), 2000);
});
promise.then(val => {
if (val === 'Promise resolved') {
console.log('异步操作完成');
}
});
```
阅读全文