👇这篇文章非常重要,值得单独列出来

TOLEARN 👇课没学完
image.png


其他


关键概念辨析

for in 和for of

简单说,for in是遍历键名,for of是遍历键值

💡: in 的逻辑比较简单,只是在里面,so是属性的key ; of 有拥有的含义,so 是 value

  1. let arr = ["a","b"];
  2. for (a in arr) {
  3. console.log(a);//0,1
  4. }
  5. for (a of arr) {
  6. console.log(a);//a,b
  7. }
  8. //提示:for...in不应该用于迭代一个关注索引顺序的 Array。
  1. const scores = {
  2. '张三':80,
  3. '李四':100,
  4. '王五':60,
  5. };
  6. for(let name in scores){
  7. console. log(name, scores[name]);
  8. //分别输出张三,80 李四,100 王五,60
  9. }
  1. const scores = {
  2. '张三':80,
  3. '李四':100,
  4. '王五':60,
  5. };
  6. for(let [name, score] of Object.entries(scores)){
  7. console. log(name, score);
  8. }
  9. //分别输出张三,80 李四,100 王五,60

深层次使用参考 TOLEARN⭐

https://segmentfault.com/q/1010000006658882 for in 遍历的是可枚举属性,for of 遍历的是可迭代

https://www.jianshu.com/p/c43f418d6bf0

对象

ES2015 引入了更加简洁的 for…of 循环,可以用它来遍历可迭代对象,例如数组:

  1. for (const currentValue of a) {
  2. // Do something with currentValue
  3. }

ECMAScript 5 增加了另一个遍历数组的方法,forEach():

自定义对象⭐⭐⭐

内部函数

闭包⭐⭐⭐


TOLEARN

JavaScript 允许以递归方式调用函数。递归在处理树形结构(比如浏览器 DOM)时非常有用。

  1. function countChars(elm) {
  2. if (elm.nodeType == 3) { // 文本节点
  3. return elm.nodeValue.length;
  4. }
  5. var count = 0;
  6. for (var i = 0, child; child = elm.childNodes[i]; i++) {
  7. count += countChars(child);
  8. }
  9. return count;
  10. }