# JavaScript 入门 Day 7

By [aow](https://paragraph.com/@ashonthewall) · 2022-03-23

---

JS基础的最后一课！

**Iterate with JavaScript While Loops**

loop是所有语言里都非常重要好用的一个概念，先来了解while loop。

    const ourArray = [];
    let i = 0;
    
    while (i < 5) {
      ourArray.push(i);
      i++;
    }
    

计算机会反复执行然后回去验证直到while后面的条件不再满足。

比如上面的代码就是从0到4添加到array中。

如果要倒序添加呢？

    const myArray = [];
    let i = 5;
    
    while (i >= 0){
      myArray.push(i);
      i --;
    }
    

**Iterate with JavaScript For Loops**

For loops更简洁，不需要额外设定i=多少多少了，直接在loop中规定。

    const myArray = [];
    
    for (let i = 1; i <= 5; i ++){
      myArray.push(i);
    }
    

非常简洁美丽。

**Iterate Odd Numbers With a For Loop**

**Count Backwards With a For Loop**

奇数偶数的话，只需要把 ++变成 +=2即可/或者-=2。

    const myArray = [];
    
    for (let i = 1; i < 10; i += 2) {
      myArray.push(i);
    }
    

**Iterate Through an Array with a For Loop**

如果给你一个myArr = \[2, 3, 4, 5, 6\]; 怎么把里面所有的数字加起来？

用for loop很容易做到。

先设定一个variable = 0，然后一一遍历myArr中所有数字，每次都把碰到的数字加上去。这个myArr里有5个数字，如果碰到其它长度的array怎么办？没关系，我们只需要把 i < arr.length即可，任何长度都可以解决。

    const myArr = [2, 3, 4, 5, 6];
    
    let total = 0;
    for (let i = 0; i < myArr.length; i ++) {
      total += myArr[i];
    }
    

**Nesting For Loops**

稍微有点烧脑，类似矩阵。我们之前说过，用array\[i\]\[j\]\[z\]这样的形式，能够取到任何复杂array到任何一个data。这里也是一样的道理。相当于我们在run arr\[i\]的基础上，再用loop run arr\[i\]\[j\]，loop上叠loop，就能让计算机遍历所有的数字。如果是三层loop呢？那就for loop三层，像盗梦空间一样。

    function multiplyAll(arr) {
      var product = 1;
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i].length; j++) {
          product *= arr[i][j];
        }
      }
      return product;
    }
    

**Iterate with JavaScript Do...While Loops**

另外一个有意思的loop结构，

do {

    ……..
    

} while ( …);

意思和while loop一样， 不同点在于，无论while (..) 里面对条件满不满足，do … while loop的结构保证了do{..}里面的代码起码会跑一次。

    const myArray = [];
    let i = 10;
    
    do {
      myArray.push(i);
      i ++;
    } while (i < 10);
    

这里的i=10一开始就不符合 i < 10的条件了，但myArray还是会包含10，因为代码已经跑了一次。

**Replace Loops using Recursion**

除了loop，我们还可以用recursion这个方法套娃。

类似于f(n) = f(n-1)\*f(n-2)这样的方程式，我们数学里很熟悉了吧。但在程序里，需要设立一个中止点，比如(0>=0);之类的，不然计算机会无限运行下去。

    function sum(arr, n) {
      if(n <= 0) {
        return 0;
      } else {
        return sum(arr, n - 1) + arr[n - 1];
      }
    }
    

**Profile Lookup**

很好的练习，接近解决实际问题，建议复习下上面的nesting for loop这个知识点。

**Generate Random Fractions with JavaScript**

**Generate Random Whole Numbers with JavaScript**

**Generate Random Whole Numbers within a Range**

Math.random( )生成 \[0,1)的随机数。

用\*来扩大范围。

用Math.floor( )包住来取整。

    function randomWholeNum() {
    
      return Math.floor(Math.random() * 10);
    }
    

如果不是从0开始，用这个乘数

    Math.floor(Math.random() * (max - min + 1)) + min
    

**Use the parseInt Function**

**Use the parseInt Function with a Radix**

parseInt( )的功能，就是把string转换成interger

    function convertToInteger(str) {
      return parseInt(str);
    }
    

parseInt( )里面再加一个radix的parameter，就可以轻松完成数字进制的转换.

    function convertToInteger(str) {
      return parseInt(str, 2);
    }
    
    convertToInteger("10011");
    

上面这个parseInt(str,2)中的2就是告诉计算机这个str是二进制的一个数，输出一个转化成十进制的integer。

**Use the Conditional (Ternary) Operator**

一行简写版的if statement

学会了确实很好用，基本结构: a ? b : c

a是condition

b是true的输出

c是false的输出

    function checkEqual(a, b) {
      return a === b ? "Equal" : "Not Equal";
    }
    

对于小白来说，适用于很简单的if statement，复杂的，咱还是规规矩矩把基本的用会了再来耍酷。

**Use Multiple Conditional (Ternary) Operators**

复杂的来了。

把else, else if什么的统统换成 : 来代替。

    function checkSign(num) {
      return num > 0 ? "positive"
        : num < 0 ? "negative"
        :  "zero";
    }
    

**Use Recursion to Create a Countdown**

这个练习回顾了recursion。

//注意，push是加在末尾的，练习的要求是加在开头，用什么呢？之前有讲过。

    function countdown(n){
      if (n < 1){
        return [];
      } else {
        let countArray = countdown(n - 1);
        countArray.unshift(n);
        return countArray;
      }
    }
    

**Use Recursion to Create a Range of Numbers**

更进一步的练习。

道理是一样的，把n换成endNum, n-1换成endNum -1 就可以了。

    function rangeOfNumbers(startNum, endNum) {
      if (startNum === endNum) {
        return [startNum];
      } else {
        let number = rangeOfNumbers(startNum, endNum - 1);
        number.push(endNum);
        return number;
      }
    };
    

好了，JS基础知识就全部学完了，我们用了7天，对于小白来说还是可以的。希望小伙伴们好好巩固，常加复习～

有什么问题，可以找我留言

这里和这里可以找到我

[https://discord.gg/madnfts](https://discord.gg/madnfts)

[https://discord.gg/Z25p8gkZWx](https://discord.gg/Z25p8gkZWx)

---

*Originally published on [aow](https://paragraph.com/@ashonthewall/javascript-day-7)*
