博客列表 >实例演示数组-对象解构|常用流程控制

实例演示数组-对象解构|常用流程控制

葡萄枝子
葡萄枝子原创
2020年12月29日 23:07:05589浏览

实例演示数组-对象解构|常用流程控制

  1. 实例演示数组与对象的解构;
  2. 实例演示常用的流程控制方法

1. 实例演示数组与对象的解构

  • 1.1 数组解构
  1. // 数组解构
  2. const arr = ['a', 'b', 3];
  3. let [arr1, arr2, arr3] = arr;
  4. // console 输出
  5. /*
  6. arr1 = a
  7. arr2 = b
  8. arr3 = 3
  9. */
  10. console.log(`arr1 = ${arr1}\narr2 = ${arr2}\narr3 = ${arr3}`);
  • 1.2 对象解构

对象解构,等号两边数据类型要一致

  1. // 对象解构
  2. const obj = {
  3. id: 1,
  4. name: 'description',
  5. };
  6. ({id, name, custom = 'default'} = obj);
  7. // console 输出
  8. /*
  9. id = 1
  10. name = description
  11. custom = default
  12. */
  13. console.log(`id = ${id}\nname = ${name}\ncustom = ${custom}`);
  • 上面两例控制台输出图

数组与对象的解构

2. 实例演示常用的流程控制方法

2.1 流程控制:分支

  • 单分支
  1. // 单分支
  2. // 输出 hello world!
  3. if (true) console.log('hello world!');
  • 双分支
  1. // 双分支
  2. // 输出 yes
  3. if (true) console.log('yes');
  4. else console.log('no');
  5. // 三元运算双分支
  6. // 输出 on
  7. let checked = true ? 'on' : 'off';
  8. console.log(checked);
  • 多分支
  1. // 多分支
  2. // 输出 n = 10
  3. let n = 10;
  4. switch(n) {
  5. case 1:
  6. console.log(`n = 1`);
  7. break;
  8. case 2:
  9. console.log(`n = 2`);
  10. default:
  11. console.log(`n = ${n}`);
  12. }

2.2 流程控制:循环

  • while 循环

while 循环,入口判断型,出口判断型

  1. const data = ['a', 'b', 3];
  2. // while 循环 - 入口判断型
  3. // 输出 a b 3
  4. let i = 0;
  5. while(i < data.length) {
  6. console.log(data[i]);
  7. i++;
  8. }
  9. // while 循环 - 出口判断型
  10. // 输出 a b 3
  11. i = 0;
  12. do {
  13. console.log(data[i]);
  14. i++;
  15. } while(i < data.length);
  • for 循环

for 循环,for in 数组和对象遍历,for of 数组遍历

  1. // for 循环
  2. // 输出 a b 3
  3. for (i = 0; i < data.length; i++) {
  4. console.log(data[i]);
  5. }
  6. // for 循环 - 数组和对象遍历
  7. // for in 数组遍历 - 输出 a b 3
  8. for (i in data) {
  9. console.log(data[i]);
  10. }
  11. // for in 对象遍历
  12. /*
  13. console 输出
  14. 1
  15. description
  16. custom value
  17. */
  18. const dataObj = {
  19. id: 1,
  20. name: 'description',
  21. 'custom key': 'custom value',
  22. };
  23. for (let key in dataObj) {
  24. console.log(dataObj[key]);
  25. }
  26. // for of 数组遍历
  27. // 输出 a b 3
  28. for (let value of data) {
  29. console.log(value);
  30. }
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议