实例演示数组-对象解构|常用流程控制
- 实例演示数组与对象的解构;
- 实例演示常用的流程控制方法
1. 实例演示数组与对象的解构
- 1.1 数组解构
// 数组解构
const arr = ['a', 'b', 3];
let [arr1, arr2, arr3] = arr;
// console 输出
/*
arr1 = a
arr2 = b
arr3 = 3
*/
console.log(`arr1 = ${arr1}\narr2 = ${arr2}\narr3 = ${arr3}`);
- 1.2 对象解构
对象解构,等号两边数据类型要一致
// 对象解构
const obj = {
id: 1,
name: 'description',
};
({id, name, custom = 'default'} = obj);
// console 输出
/*
id = 1
name = description
custom = default
*/
console.log(`id = ${id}\nname = ${name}\ncustom = ${custom}`);
- 上面两例控制台输出图
2. 实例演示常用的流程控制方法
2.1 流程控制:分支
- 单分支
// 单分支
// 输出 hello world!
if (true) console.log('hello world!');
- 双分支
// 双分支
// 输出 yes
if (true) console.log('yes');
else console.log('no');
// 三元运算双分支
// 输出 on
let checked = true ? 'on' : 'off';
console.log(checked);
- 多分支
// 多分支
// 输出 n = 10
let n = 10;
switch(n) {
case 1:
console.log(`n = 1`);
break;
case 2:
console.log(`n = 2`);
default:
console.log(`n = ${n}`);
}
2.2 流程控制:循环
- while 循环
while 循环,入口判断型,出口判断型
const data = ['a', 'b', 3];
// while 循环 - 入口判断型
// 输出 a b 3
let i = 0;
while(i < data.length) {
console.log(data[i]);
i++;
}
// while 循环 - 出口判断型
// 输出 a b 3
i = 0;
do {
console.log(data[i]);
i++;
} while(i < data.length);
- for 循环
for 循环,
for in
数组和对象遍历,for of
数组遍历
// for 循环
// 输出 a b 3
for (i = 0; i < data.length; i++) {
console.log(data[i]);
}
// for 循环 - 数组和对象遍历
// for in 数组遍历 - 输出 a b 3
for (i in data) {
console.log(data[i]);
}
// for in 对象遍历
/*
console 输出
1
description
custom value
*/
const dataObj = {
id: 1,
name: 'description',
'custom key': 'custom value',
};
for (let key in dataObj) {
console.log(dataObj[key]);
}
// for of 数组遍历
// 输出 a b 3
for (let value of data) {
console.log(value);
}