免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
JavaScript 基礎(chǔ)

JavaScript

使用JS的幾種寫法

  1. 行內(nèi)式的js 直接寫道元素的內(nèi)部

    <button type="button" value="須彌" onclick="alert('納西妲')"></button>

  2. 內(nèi)嵌式j(luò)s

  3. 引入式

<script src="my.js"></script>

JS注釋

單行注釋與多行注釋

    <script>
        // 單行注釋    快捷鍵 CTRL+ /
        /* 
        多行注釋   快捷鍵: shift + alt + a
        */ 
    </script>

JS的輸入輸出語句

prompt('請輸入你的年齡'); 輸入框

alert('計算機結(jié)果是') 彈出框

console.log('程序員可見,在瀏覽器控制臺'); 瀏覽器控制臺console可見

doucument.write('要輸出的內(nèi)容'); 向body內(nèi)輸出內(nèi)容,如果輸出內(nèi)容寫的是標簽,也會解析成網(wǎng)頁元素

<!DOCTYPE html>

<html>

<head>

    <meta charset='utf-8'>

    <meta http-equiv='X-UA-Compatible' content='IE=edge'>

  <title>Page Title</title>

    <script>

    *//輸入框*

    prompt('請輸入你的年齡');

    *//彈出警示框*

    alert('計算機結(jié)果是');

    console.log('程序員可見,在瀏覽器控制臺');

  </script>

</head>

<body>
</body>

</html>

變量

什么是變量?

變量在JavaScript中就是用一個變量名表示,變量名是大小寫英文、數(shù)字、 $ 和 _ 的組合,且不能用數(shù)字開頭。變量名不能是JavaScript的關(guān)鍵字,如 if 、 while 等。

用來存儲數(shù)據(jù)的一個空間。

變量的使用

申明一個變量用 let 語句。

變量使用分兩步:1. 聲明變量 2. 賦值

如: let age; //聲明變量,age是聲明的變量

變量初始化 let age = 19 ;

注意: let 聲明變量只能聲明一次。var則可以聲明多次,但是不推薦。

案例1:

<!DOCTYPE html>

<html>

<head>

    <meta charset='utf-8'>

    <meta http-equiv='X-UA-Compatible' content='IE=edge'>

  <title>Page Title</title>

    <meta name='viewport' content='width=device-width, initial-scale=1'>

    <script>

    let myname = "nahida";

    let address = "須彌";

    let age = 500;

    let email = 'GenshinImpact@mihoyo.com';

    let salary = 2000;

    console.log('我的名字是%s,我住在%s,我%s了,我的郵箱是%s,我的工資是%s',myname,address,age,email,salary);

  </script>

</head>

<body>

</body>

</html>

案例2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <title>變量使用</title>
    <script>
        // 1. 請輸如用戶名字
        let myName = prompt('請輸入你的名字');
        //2. 彈出
        alert(myName);
    </script>
</head>
<body>

</body>
</html>

變量的語法擴展

一個變量被重新賦值后,原先的賦值被覆蓋,一最后一次賦值為準。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        let myname = "Nihida";
        alert(myname);
        myname = 'Barbatos';
        alert(myname);

        //同時聲明多個變量
        let age = 6000, address = '璃月', salary = 0;

        //聲明變量的特殊情況
        //1. 只聲明不賦值  結(jié)果是  undefined
        //2. 不聲明,不賦值 結(jié)果是  Error報錯
        //3. 不聲明,直接賦值  結(jié)果是 10   不提倡,會變成全局變量

    </script>
</head>
<body>

</body>
</html>

變量的命名規(guī)范

  • 由字母、數(shù)字、下劃線、美元符號($)組成

  • 嚴格區(qū)分大小寫

  • 不能以數(shù)字開頭,可以下劃線、美元符號開頭,其他符號不允許

  • 不能是js的保留字、關(guān)鍵字:let、console、name等

  • 變量必須有意義

  • 遵守駝峰命名。首字母小寫,后面的單詞的首字母需要大寫

交換兩個變量的值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>交換兩個變量的值</title>
    <script>
      let nameA = 'Nahida',
              nameB = 'Barbatos',
              temp ;
      alert(nameA);
      alert(nameB);
      console.log(nameA,nameB)
      temp = nameA;
      nameA = nameB;
      nameB =temp;
      console.log(nameA,nameB)
    </script>
</head>
<body>

</body>
</html>

數(shù)組的基本使用

數(shù)組Array 是一種可以按順序保存多個數(shù)據(jù)

let arr = [];

取值:arr[] 數(shù)組名[下標]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  let arr = ['nahida','barbatos','Morax','Beelzebul'];
  console.log(arr);
  console.log(arr[0]);
</script>

</body>
</html>

數(shù)據(jù)類型

計算機顧名思義就是可以做數(shù)學計算的機器,因此,計算機程序理所當然地可以處理各種數(shù)值。但是,計算機能處理的遠不止數(shù)值,還可以處理文本、圖形、音頻、視頻、網(wǎng)頁等各種各樣的數(shù)據(jù),不同的數(shù)據(jù),需要定義不同的數(shù)據(jù)類型。在JavaScript中定義了以下幾種數(shù)據(jù)類型:

  1. Number

  2. 字符串

  3. 布爾值

  4. 比較運算符

  5. null和undefifined

  6. 數(shù)組

  7. 對象

數(shù)字型Number

JavaScript不區(qū)分整數(shù)和浮點數(shù),統(tǒng)一用Number表示,以下都是合法的Number類型:

123; // 整數(shù)
123 0.456; // 浮點數(shù)
0.456 1.2345e3; // 科學計數(shù)法表示1.2345x1000,等同于1234.5 
-99; // 負數(shù) 
NaN; // NaN表示Not a Number,當無法計算結(jié)果時用NaN表示 
Infinity; // Infinity表示無限大,當數(shù)值超過了JavaScript的Number所能表示的最大值時,就 表示為Infinity
-Infinity;  //無窮小

計算機由于使用二進制,所以,有時候用十六進制表示整數(shù)比較方便,十六進制用0x前綴和0-9,a-f表示,例如: 0xff00 , 0xa5b4c3d2 ,等等。八進制以0開頭,如 010、012。

初始化: let age = 123;

  • isNaN() 這個方法是判斷是否是數(shù)字,是數(shù)字返回true,不是就返回false。

//isNaN() 這個方法是判斷是否是數(shù)字,是數(shù)字返回true,不是就返回false
let nameC = "ZhongLi"
console.log(isNaN(nameC));
let age = 100;
console.log(isNaN(age));

字符類型String

字符串是以單引號'或雙引號"括起來的任意文本,比如 'abc' , "xyz" 等等。請注意, '' 或 "" 本身只是一種表示方式,不是字符串的一部分,因此,字符串 'abc' 只有a , b , c 這3個字符。

可以單引號套雙引號,也可以雙引號套單引號:" ' ' " 、 ' " " ',不可以單引號套單引號或者雙引號套雙引號。

字符串轉(zhuǎn)義字符,都是 \ 開頭,但是這些轉(zhuǎn)義字符都是寫到引號里面。

案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
      alert('須彌什么時候開? \n  我不知道,"這個一定是米哈游干的"')        //   \n 換行
    </script>
</head>
<body>

</body>
</html>

字符串長度以及拼接

字符串的length屬性可以獲取整個字符的長度。

字符串的拼接 + 'str1' + 'str2' 字符串類型 + 任何類型 = 拼接智慧的新字符串

符號 + 數(shù)值是相加,字符是相連

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
      alert('須彌什么時候開? \n  我不知道,"這個一定是米哈游干的"')
      let str = '須彌什么時候開? \n  我不知道,"這個一定是米哈游干的"';
      console.log(str.length);

      console.log(str + '\n ——原神3.0版本開');       //   \n 換行
      console.log('nahida' + true)   //  nahidatrue
    </script>
</head>
<body>

</body>
</html>

字符串拼接加強

變量不要寫在字符串里面,可以:字符串+ 變量 + 字符串

let age  = 500;
console.log('nahida age is ' + age + 'years');

案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script>
    let age = prompt('請輸入你的年齡');
    let str = "您今年" + age + '歲了';
    alert(str);
  </script>
</head>
<body>

</body>
</html>

模板字符串

符號:

  • ··

  • 在英文輸入模式下tab鍵上方的的那個鍵(1 左邊的那個鍵)

  • 內(nèi)容拼接變量時,用${ } 包住

  • 這玩意可以支持換行。

舉例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script>
    let age = prompt('請輸入你的年齡');
    let str = `您今年 ${age} 歲了`;
    alert(str);
    document.write(`大家好,我今年${age}歲了`);
    document.write(`
                        <div>
                            <p>Beelzebul</p>
                        </div>
    `)
  </script>
</head>
<body>

</body>
</html>

布爾值Boolean、undefined和null

布爾值和布爾代數(shù)的表示完全一致,一個布爾值只有 true 、 false 兩種值,要么是 true ,要么是 false ,可以直接用 true 、 false 表示布爾值,也可以通過布爾運算計算出來:

true; // 這是一個true值 
false; // 這是一個false值 
2 > 1; // 這是一個true值 
2 >= 3; // 這是一個false值

let flag = true;
ver flag2 = false;
console.log(flag + 1)     // 2
console.log(flag + 1)     // 1

let letiable = undefined;      //undefine 只聲明,不賦值
console.log(letiable + 1);    //NaN
console.log(letiable + 'Nahida');    //undefinedNahida

let space = null;          //表示為空
console.log(space + 1);   //1
console.log(space + 'Nahida');   //nullNahida

獲取變量的類型

typeof *

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script>
    let age =10,
            str = 'Nahida',
            flag = true,
            leti = undefined,
            nulli = null;
    console.log(typeof age);
    console.log(typeof str);
    console.log(typeof flag);
    console.log(typeof leti);
    console.log(typeof nulli);     //object
    console.log(typeof age+ '11')  //number11    先判斷age的類型,然后和11 組成字符串為number11
  </script>
</head>
<body>

</body>
</html>

字面量

在源碼中一個固定值的表示法,通俗來說,就是字面量表示如何表達這個值。(不重要)

數(shù)據(jù)類型轉(zhuǎn)換

轉(zhuǎn)換為字符串類型

  • toString() :轉(zhuǎn)換成字符串

    let num = 1;
    alert(num.toString());
  • String() 強制轉(zhuǎn)換額為字符串

    let num = 1;
    alert(String(num));
  • 加號拼接 和字符拼接的結(jié)果都是字符串(更喜歡這個,一般稱為 隱式轉(zhuǎn)換)

    let num = 1;
    alert(num + '字符串');

轉(zhuǎn)化為數(shù)字型(重點)

parseInt(String)和parseFloat(String) *(重點)
parseInt('87');     //會得到整數(shù),向下取整
parseInt('87px');   //只保留數(shù)字,如果非數(shù)字開頭,則NaN
parseFloat('114.514');    //浮點數(shù)
parseFloat('114.514px');    //浮點數(shù),只保留數(shù)字,如果非數(shù)字開頭,則NaN
Number()強制轉(zhuǎn)換函數(shù) 和隱式轉(zhuǎn)換

Number()內(nèi)只能放數(shù)字類型的字符,其他的會報錯

隱式轉(zhuǎn)換:某些運算符被執(zhí)行時,系統(tǒng)內(nèi)部自動將數(shù)據(jù)類型進行轉(zhuǎn)換。

利用算數(shù)運算 - * / 隱式轉(zhuǎn)換,加號除外。

補充

 + 號兩邊只要一個是字符串,就會把另外一個轉(zhuǎn)成字符串

 + 號作為正號解析可以轉(zhuǎn)換為Number類型

//Number(變量)
let num = '114.514'
Number(num)    //強制轉(zhuǎn)換函數(shù)

//利用算數(shù)運算  - * / 隱式轉(zhuǎn)換
console.log(num - 0);         //114.514
console.log('120' - '110');   //10
console.log(num * 1);         //114.514
console.log(+num);         //114.514
console.log(+'11' + 11)    //22
計算年齡案例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script>
    let ageA = prompt("輸入你出生年");
    let ageB = prompt('今年年數(shù)');
    let age = 0;
    ageA = parseInt(ageA);
    ageB = parseInt(ageB);
    age = ageB - ageA;
    alert(ageB + '年時,你' + age + '歲了');
  </script>
</head>
<body>

</body>
</html>

轉(zhuǎn)型為布爾行

Boolean()函數(shù)

Boolean('true');
Boolean('false');

代表空、否定的值會被轉(zhuǎn)換為false,如 '' 、 0 、 NaN 、 null 、 undefined。其他非空字符、數(shù)字等類型皆轉(zhuǎn)換為true。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script>
    let myname = prompt('請輸入你的姓名');
    let age = prompt('請輸入你的年齡');
    let sex = prompt('請輸入你的性別');
    alert('您的姓名是' + myname
            +'\n 您的年齡是' + age
            +'\n 您的性別是' + sex);
  </script>
</head>
<body>

</body>
</html>

案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  let price = +prompt('請輸入商品價格'),
          num = +prompt('數(shù)量'),
          address = prompt('輸入你的地址'),
          total = price * num;
  document.write(`
    <table>
    <caption>
        <h2>訂單確認</h2>
    </caption>
    <tr>
        <th>商品名稱</th>
        <th>商品價格</th>
        <th>商品數(shù)量</th>
        <th>總價</th>
        <th>收貨地址</th>
    </tr>
    <tr>
        <td>小米12 pro </td>
        <td>${price} 元</td>
        <td>${num} 元</td>
        <td>${total} </td>
        <td>${address} </td>

</tr>
</table>
  `)

</script>

</body>
</html>

排錯思路

運算符

算數(shù)運算符

運算符號(加、減、乘、除、取余):

//   +   -    *     /     %   

 console.log(0.7 * 10);   //7.00000000001
 let num = 0.1 + 0.2  ;
 console.log(num = 0.3);   //false

注意:浮點數(shù)在算數(shù)運算里面會出現(xiàn)問題,不能用浮點數(shù)做對比。

算數(shù)運算符是有優(yōu)先級的,先乘除后加減,有括號先算括號里。

表達式與返回值:
// 是由數(shù)字、運算符、變量等組成的式子 為表達式
console.log(1 + 1);    //2 返回值

遞增遞減運算符

++i i++ 單獨使用時候效果一樣的,但直作為 n = i ++ 或者 n = ++i ,效果是不一樣的

//形如:
let n=0, i = 0;

++i        // i = i+1
n = ++i    //先自加,再賦值
i++        // i = i+1
n = i++    //先賦值,再自加

--i
i--

i +=2  //  i = i + 2
i -=2  //  i = i - 2
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script>
    let i= 0, n= 2;
    n = i++;
    console.log(n);  // n = 0
    console.log(i);  // i = 1
    n = ++i;         // n = 2 ; i = 2
    console.log(n);  // 2

    let e = 12;
    f = e++ + ++e;   //  10 + 12  = 22
    console.log(f);  //  22
  </script>
</head>
<body>

</body>
</html>

比較常見的是 單獨的使用 i++ 。但是其他也要掌握,面試和考試的時候為難人的

比較運算符

當我們對Number做比較時,可以通過比較運算符得到一個布爾值:

2 > 5; // false 
5 >= 2; // true 
7 == 7; // true

實際上,JavaScript允許對任意數(shù)據(jù)類型做比較:

false == 0; // true 
false === 0; // false

要特別注意相等運算符 == 。JavaScript在設(shè)計時,有兩種比較運算符:

第一種是 == 比較,它會自動轉(zhuǎn)換數(shù)據(jù)類型再比較,很多時候,會得到非常詭異的結(jié)果;

第二種是 === 比較,它不會自動轉(zhuǎn)換數(shù)據(jù)類型,如果數(shù)據(jù)類型不一致,返回 false ,如果一致,再比較。

由于JavaScript這個設(shè)計缺陷,不要使用== 比較,始終堅持使用 === 比較。 因為===是比較同類型的數(shù)值,優(yōu)先使用全等符號===。

另一個例外是 NaN 這個特殊的Number與所有其他值都不相等,包括它自己:

NaN === NaN; // false

唯一能判斷 NaN 的方法是通過 isNaN() 函數(shù):

isNaN(NaN); // true

最后要注意浮點數(shù)的相等比較:

1 / 3 === (1 - 2 / 3); // false

這不是JavaScript的設(shè)計缺陷。浮點數(shù)在運算過程中會產(chǎn)生誤差,因為計算機無法精確表示無限循環(huán)小數(shù)。要比較兩個浮點數(shù)是否相等,只能計算它們之差的絕對值,看是否小于某個閾值:

Math.abs(1 / 3 - (1 - 2 / 3)) < 0.0000001;   // true

邏輯運算符

&& 與

|| 或

! 非

與其他計算機語言的使用方法一致。

其他情況:

短路運算(邏輯中斷):當有多個表達式(值)時,左邊的表達式可以確定結(jié)果時,就不再繼續(xù)運算右邊的表達式的值。

邏輯與: 表達式1 && 表達式2
  • 如果表達式1 為真 ,則返回表達式2

  • 如果表達式1 為假, 則返回表達式1

console.log(123 && 456)   //456
console.log(0 && 456)   // 0
console.log(0 && 459+2356 && 100*235356)  // 0

//如果有空、為0或者否定的,為假.其余的是真的
邏輯或:表達式1 || 表達式2
  • 如果表達式1為真,返回表達式1

  • 如果表達式1為假,返回表達式2

console.log(123 || 456)   //123
console.log(0 || 456)   // 456
console.log(1 || 459+2356 || 100*235356)  // 1
console.log(0 || 456 || 456+123)   //  456

//如果有空、為0或者否定的,為假.其余的是真的

let num = 0;
console.log(123 || num++);     //123   123為真,num++不執(zhí)行
console.log(num);   // 0

賦值運算符

i= 0;   
n+=2;  // n = n+2
e-=2;  // e = e-2
v*=10;  // v = v*3
k/=13;  // k = k/13
p%=19;  // p = p%19

運算符的優(yōu)先級

優(yōu)先級越小越優(yōu)先

流程控制

順序結(jié)構(gòu)、分支結(jié)構(gòu)、循環(huán)結(jié)構(gòu)

順序結(jié)構(gòu)

按照代碼的先后順序,依次執(zhí)行

分支結(jié)構(gòu)

根據(jù)不同條件,執(zhí)行不同的路徑代碼

if分支

//語法結(jié)構(gòu)
if(條件表達式){
   //條件成立時執(zhí)行的執(zhí)行語句
   }

//執(zhí)行思路: 如果if里面的條件表達式為真,則執(zhí)行大括號里邊的執(zhí)行語句
//舉例

if(5 > 3){
    alert(true);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
      let age = prompt("請輸入您的年齡")
//      age = parseFloat(age);
      if (age > 18){
        alert('您可以進入網(wǎng)吧了')
      }else {
        alert('您未滿18歲或者輸入年齡有誤')
      }
    </script>
</head>

<body>

</body>
</html>

if-else分支

if(條件表達式){
    //條件為真,執(zhí)行的語句
} else{
    //條件為假。執(zhí)行的語句
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
      let year = prompt("輸入年份");
      year = parseInt(year);

      if (year % 4 ==0 && year%100 !=0 || year%400 ==0){
        alert(year + "是閏年");
      }else {
        alert(year + "不是閏年");
      }

    </script>
</head>
<body>

</body>
</html>

if -else if多分支

if(條件一){
   //滿足條件一執(zhí)行的語句1
   }else if(條件二){
   //滿足條件二執(zhí)行的語句2         
   }else if(條件三){
   //滿足條件三執(zhí)行的語句3      
   }else{
   //都不滿足的時候,執(zhí)行的語句   
   }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
      let performance = 0
      while (true){
        performance =prompt("請輸入你的成績");
        performance = parseFloat(performance);
        if (performance >= 90){
          alert('成績優(yōu)秀');
        }else if (performance >=80 && performance < 90){
          alert('成績良好');
        }else if (performance >=60 && performance <80 ){
          alert('成績合格');
        }else {
          alert('成績不及格')
        }
      }

    </script>
</head>
<body>

</body>
</html>

三元表達式

//三元表達式
//   條件表達式 ?表達式1 :表達式2
//   條件表達式結(jié)果為真,執(zhí)行(返回)表達式1;如果條件表達式結(jié)果為假,執(zhí)行(返回)表達式2

//舉例
let num  = 5;
let result = num > 5 ? '是的' : '不是的';
console.log(result);  //是的
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
      let num = prompt("請輸入一個0~59的數(shù)字");
      let time = num<10 ? '0'+num : num;       //三元表達式一定有一個返回值
      alert(time);
    </script>
</head>
<body>

</body>
</html>

switch分支

// 主要針對特定值,執(zhí)行對應(yīng)的語句
// switch (判斷表達式) {
//   case value1:
//     執(zhí)行語句一;
//     break;
//   case value2:
//     執(zhí)行語句一;
//     break;
//   ...
//   default:
//     執(zhí)行最后的語句;
//
// }

//如果表達式的值與case的value值匹配得上,就執(zhí)行相應(yīng)的語句。如果都沒有匹配得上,就執(zhí)行default里面的語句

//switch的注意事項:
//1. 表達式里邊一般寫為變量
//2. case的value值與判斷表達式的值相匹配的時候是全等關(guān)系(也就是類型和數(shù)據(jù)值是一致的)
//3. break;沒有的話,會繼續(xù)執(zhí)行接下來的程序語句
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
      switch (2) {
        case 1:
          alert(1);
          break;
        case 2:
          alert(2);
          break;

        default:
          alert(null);

      }
    </script>
</head>
<body>

</body>
</html>

switch的注意事項:

  1. 表達式里邊一般寫為變量

  2. case的value值與判斷表達式的值相匹配的時候是全等關(guān)系(也就是類型和數(shù)據(jù)值是一致的)

  3. break;沒有的話,會繼續(xù)執(zhí)行接下來的程序語句

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
      let f = prompt('請輸入一種水果');
      switch (f){
        case '蘋果':
          alert('3.5D/kg');
          break;
        case '榴蓮':
          alert('6356D/kg');
          break;
        default:
          alert(null);
      }
    </script>
</head>
<body>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>簡易計算器</title>
</head>
<body>
<script>
  let num1 = prompt('輸入第一個數(shù)');
  let num2 = prompt('輸入第二個數(shù)');
  let sp = prompt('輸入 +-*/ 運算符');
  switch (sp) {
    case '+':
      alert(`您選擇的是加法,結(jié)果是${+num1 + +num2}`);
      break;
    case '-':
      alert(`您選擇的是減法,結(jié)果是${num1 - num2}`);
      break;
    case '*':
      alert(`您選擇的是乘法,結(jié)果是${num1 * num2}`);
      break;
    case '/':
      alert(`您選擇的是除法,結(jié)果是${num1 / num2}`);
      break;
    default:
      alert('輸入錯誤');

  }

</script>

</body>
</html>

if-if elae -else和switch的區(qū)別

  1. 一般情況下,他們兩個可以相互替換

  2. switch 語句通常處理case的值的情況,而if-else 語句更靈活

  3. switch語句進行條件判斷后直接執(zhí)行對應(yīng)的程序語句,效率更高。而if else if語句會逐一判斷各個條件,找到滿足條件為止。

  4. 當分支比較少時候,if-else比較好一些

  5. 當分支比較多的時候,switch語句的執(zhí)行效率更高一些,且結(jié)構(gòu)清晰

循環(huán)結(jié)構(gòu)

可以重復(fù)執(zhí)行某些代碼

循環(huán)退出: continue 和break

  • continue:結(jié)束本次循環(huán),繼續(xù)下一次循環(huán)

  • break:直接退出while循環(huán)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>
        let i = 1;
        while (i < 6){
            if (i===3){
                i++;
                continue
            }
            if (i===4){
                i++;
                break
            }
            document.write(`我要吃第${i}個包子<br>`);
            i++;
        }

        for(let n = 1; n < 5; n++ ){
            if(n === 2){
                continue;
            }
            if(n === 4){
                break;
            }
            document.write(n);
        }
    </script>

</body>
</html>

for循環(huán)

for(初始化變量;循環(huán)條件;操作表達式){
    //循環(huán)體
}

//初始變量就是用let 聲明的一個普通變量,通常用于作為計數(shù)器使用
//條件表達式 就是用來決定每一次循環(huán)是否繼續(xù)執(zhí)行 就是終止的條件
//操作條件 是每次循環(huán)最后執(zhí)行的代碼 經(jīng)常用于計數(shù)器變量進行更新

for(let i = 0 ; i <10 ; i++){
    alert('打印10次');
}

// 先執(zhí)行 let = 0
// 再執(zhí)行 i <100   判斷條件,滿足進行下一步
// 執(zhí)行循環(huán)體  alert('打印100次');
// 執(zhí)行 i++
// 回到 執(zhí)行 i <100   判斷條件... 重復(fù)執(zhí)行
// 執(zhí)行到?jīng)]有滿足i <100的判斷條件,退出循環(huán)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  //求1-100 之間的偶數(shù)和
  let sum = 0;
  for (let i = 0; i <= 100; i++) {
    if (i % 2 ===0){
      sum +=i;
    }

  }
  document.write(sum);

  //頁面中打印5個小星星
  for (let n = 0; n < 5; n++) {
    document.write('?');
  }
</script>

</body>
</html>

循環(huán)遍歷數(shù)組:

let arr = ['Nahida','Barbatos','Morax','Beelzebul'];
for (let j = 0; j < arr.length; j++) {
  document.write(`${arr[j]} <br>`)
}
循環(huán)嵌套
for(外部循環(huán)){
    for(內(nèi)部循環(huán)){
        循環(huán)體;
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; j++) {
      document.write(`※`)
    }
    document.write('<br>');
  }
</script>

</body>
</html>

案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>三角形</title>
</head>
<body>
<script>
  for (let i = 1; i < 6; i++) {
    for (let j = 1; j <= i; j++) {
      document.write(`★`)
      }
    document.write('<br>');
  }
</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>三角形</title>
  <style>
    div{
      display: inline-block;
      height: 25px;
      line-height: 25px;
      background-color: aqua;
      margin: 5px;
      padding: 0 10px;
      border: 1px solid #66ccff;
      box-shadow: 2px 2px #66ccff;
      color: #1f9763;
      border-radius: 5px;
    }
  </style>
</head>
<body>
<script>
  for (let i = 1; i < 10; i++) {
    for (let j = 1; j <= i; j++) {
      document.write(`
        <div>${i} x ${j} = ${i * j} </div>
      `)
      }
    document.write('<br>');
  }
</script>

</body>
</html>

斷點調(diào)試:

  • 瀏覽器,快捷鍵F12(鼠標右鍵->檢查)

  • 選擇 ”Source“

  • 選擇想要測試的代碼,點擊對應(yīng)的行號,設(shè)置斷點

  • 刷新瀏覽器

  • 點擊一個 "向下彎曲的箭頭 ,下面有一個點 " 的圖標,逐步測試

while循環(huán)

while() 在...區(qū)間

while(循環(huán)條件){
        //重復(fù)執(zhí)行(循環(huán)體)
}

//循環(huán)體為真時,重復(fù)執(zhí)行循環(huán)體
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  let i = 1;
  while (i <= 10){
    document.write(`考研上岸,月薪過萬<br>`);
    i+=2;
  }

  //計算1~100的累加
  let  j = 1;
  let sum = 0;
  while (j <=100){
      sum +=j;
      j++;
  }
  document.write(sum)

  //計算1-100之間的偶數(shù)和
  let n = 1;
  let sumD = 0;
  while (n <= 100){
      if (n % 2 ===0){
          sumD = sumD + n;
      }
      n++;
  }
  document.write(sumD)
</script>

</body>
</html>

do...while循環(huán)(很少用)

練習
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>簡易ATM</title>
</head>
<body>
<script>
  let money  = 1000;
  while (true){
    let str = prompt(`請輸入您的操作:
          1. 存錢
          2. 取錢
          3. 查看余額
          4. 退出
    `);
    if ( str === '4') {
      break;
    }
    switch (str){
      case '1':
        let store = +prompt('請輸入您存入的金額');
        money = money + store;
        break;

      case '2':
        let qu = +prompt('請輸入您存入的金額');
        money = money - qu;
        break;

      case '3':
        alert(`您的余額是 ${money}元`);
    }

  }
</script>

</body>
</html>

for和while的區(qū)別

  • 當如果明確了循環(huán)次數(shù)的時候推薦使用for循環(huán)

  • 當不明確循環(huán)次數(shù)的時候推薦while循環(huán)

數(shù)組

聲明語法:let arr = ['nahida','barbatos','Morax','Beelzebul']; let 數(shù)組名 = [元素1 ,元素2,元素3,]

取值:arr[0] 數(shù)組名[下標]

案例

數(shù)組求和

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  let arr = [2,6,1,7,4];
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum = sum + arr[i];
  }
  document.write(`數(shù)組求和:${sum}`);
</script>

</body>
</html>

求數(shù)組中的最大值:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  let arr = [2,6,1,77,52,25,7];
  let max_value = arr[0];
  for (let i = 0; i < arr.length; i++) {
    if (max_value < arr[i])
      max_value = arr[i];
  }
  document.write(`最大值:${max_value}`);
</script>

</body>
</html>

操作數(shù)組

增刪查改:

查詢數(shù)組: 數(shù)組[下標]

改(重新賦值):數(shù)組[下標] = 新值

增 (添加新數(shù)據(jù)) arr.push (新內(nèi)容) arr.unshift(新增的內(nèi)容)

刪 刪除數(shù)據(jù) arr.pop() arr.shift() arr.splice(操作下標 ,刪除個數(shù))

添加數(shù)組元素
  1. 這一種方法是從數(shù)組結(jié)尾添加元素,順帶返回數(shù)組長度

arr.push(元素1,元素2,元素3 ...)

  1. 這一種方法是從數(shù)組的開頭添加元素,順帶返回數(shù)組長度

    arr.unshift(元素1,元素2,元素3 ...)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  let arrA = [2,0,6,1,77,0,52,0,25,7];
  let arrB = [];
  let arrC = [];
  for (let i = 0; i < arrA.length; i++) {
    if (arrA[i] >= 10){         //將A數(shù)組大于10的元素存入B數(shù)組
      arrB.push(arrA[i]);
    }
    if (arrA[i] !== 0){         //將A數(shù)組非0的元素存入B數(shù)組
      arrC.push(arrA[i]);
    }
  }
  document.write(arrA);
  document.write(`<br>`)
  document.write(arrB);
  document.write(`<br>`)
  document.write(arrC);
</script>

</body>
</html>
刪除數(shù)組元素
  1. 從數(shù)組結(jié)尾刪除元素:arr.pop()

  2. 刪除素組的第一個元素 : arr.shift()

  3. 指定指定元素(開發(fā)常用) : arr.splice(數(shù)組下標 ,刪除個數(shù)) arr.splice(起始位置 ,刪除個數(shù)) 。

<!DOCTYPE html>
   <html lang="en">
   <head>
       <meta charset="UTF-8">
       <title>Title</title>
   </head>
   <body>
   <script>
     let arr = ['nahida','Barbatos','Morax','Beelzebul'];

     //查
     console.log(arr[0]);

     //改
     arr[2] = 'ZhongLi';
     console.log(arr[2]);

     //增
     arr.push('雷電將軍', '冰之女皇' );
     console.log(arr);

     arr.unshift('溫迪', `賣唱的`);
     console.log(arr);

     //刪
     arr.pop();
     console.log(arr.pop());    //'雷電將軍'   返回被刪除的值
     console.log(arr);

     arr.shift();
     console.log(arr.shift());   //賣唱的   返回被刪除的值
     console.log(arr);

     arr.splice(1,1)  //刪除
     arr.splice(1)  //刪除   從數(shù)組下標為1開始往后刪
     console.log(arr);

   </script>

   </body>
</html>
冒泡排序
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  let arr = [2,0,6,1,77,1,52,3,25,7];
  let temp = 0;
  for (let i = 0; i < arr.length-1; i++) {
      for (let j = 0; j < arr.length - i -1 ; j++) {
          if (arr[j+1] <arr[j]){
              temp = arr[j];
              arr[j] = arr[j+1];
              arr[j+1] = temp;
          }
      }
  }
  console.log(arr)

</script>

</body>
</html>
綜合案例

用戶輸入4個季度數(shù)據(jù),生成4個季度的柱狀圖

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
      *{
        margin: 0;
        padding: 0;
      }
      .box{
        display: flex;
        width: 700px;
        border-left: 1px solid pink;
        border-bottom: 1px solid pink;
        margin: 50px auto;
        justify-content: space-around;
        align-items: flex-end;
        text-align: center;
      }
      .box>div{
        display: flex;
        width: 50px;
        background-color: pink;
        flex-direction: column;
        justify-content: space-around;
      }
      .bax div span{
        margin-top: -20px;
      }

      .box div h4{
        margin-top:  70px;
        width: 70px;
        margin-left: -10px;
      }

    </style>
</head>
<body>
<script>
  let arr = [];
  for (let i = 0; i < 4; i++) {
    let num = +prompt(`請輸入第${i+1} 個季度的數(shù)據(jù)`);
    arr.push(num);
  }
  console.log(arr)
  document.write(`<div class="box">`)
  for (let j = 0; j < arr.length; j++) {
    document.write(`
      <div style="height: ${arr[j]}px">
         <span>${arr[j]}</span>
         <h4>第${j+1}個季度</h4>
      </div>
    `)
  }
  document.write(`</div>`)
</script>

</body>
</html>

函數(shù)

基本使用

精簡代碼,方便復(fù)用,提高開發(fā)效率。

函數(shù)的聲明語法

function 函數(shù)名(){
函數(shù)體
}

函數(shù)的調(diào)用 函數(shù)名()

函數(shù)命名的規(guī)范:

  1. 和變量名基本一致

  2. 盡量小駝峰式命名法

  3. 前綴應(yīng)該為動詞

  4. 命名建議:常用動詞約定 如 function getName(){}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>三角形</title>
  <style>
    div{
      display: inline-block;
      height: 25px;
      line-height: 25px;
      background-color: aqua;
      margin: 5px;
      padding: 0 10px;
      border: 1px solid #66ccff;
      box-shadow: 2px 2px #66ccff;
      color: #1f9763;
      border-radius: 5px;
    }
  </style>
</head>
<body>
<script>
    function fn(){
        for (let i = 1; i < 10; i++) {
            for (let j = 1; j <= i; j++) {
                document.write(`
        <div>${i} x ${j} = ${i * j} </div>
      `)
            }
            document.write('<br>');
        }
    }

    fn();
    fn();
</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  function getSum(){
    let num = 12;
    let num2 = 16;
    document.write(num + num2);
  }

  getSum();
  function getSum100(){
    let sum = 0;
    for (let i = 1; i < 101; i++) {
      sum +=i;

    }
    document.write(sum);
  }
  getSum100();
</script>

</body>
</html>

參數(shù)

需要參數(shù)的傳參。使用者可以通過傳入數(shù)據(jù),那么就需要有參數(shù)的函數(shù)。以提高函數(shù)的靈活性。

開發(fā)種盡量保持形參和實參個數(shù)一致。

function 函數(shù)名(參數(shù)列表){
函數(shù)體
}
function getSum(num1 , num2){
    let sum = num1 + num2;
    console.log(sum);
}

getSum(1,2)

// num1和num2是形參
// 1、2 是實參

案例:函數(shù)封裝求和

合理利用邏輯中斷

function getSum(x, y){
  x = x || 0;
  y = y || 0;
  console.log(x+y);
}
getSum(1,2);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  function getScore(numbers) {
    let sum = 0;
    for (let i = 0; i < numbers.length; i++) {
      sum +=numbers[i];

    }
    document.write(sum);
  }

  getScore([99,100,93]);

</script>

</body>
</html>

返回值、返回多個值

函數(shù)的返回值。當調(diào)用某個函數(shù)值的時候,函數(shù)返回一個特定的值。但是有些函數(shù)根據(jù)需求不需要返回值。

很多情況下需要返回值。

返回一個值

如果函數(shù)需要返回數(shù)據(jù)時候,使用 return關(guān)鍵字修飾 return 數(shù)據(jù) return 20

return 有立即結(jié)束函數(shù)的作用。如果函數(shù)中沒有寫return 則默認為為undefined

function fn(){
    return 20;
}

console.log(fn());

function getSum(x, y){
  x = x || 0;
  y = y || 0;
  return x+y;
}
let sum = getSum(1,2);
console.log(sum);

function fn2(){

}
let i = fn2();    //undefine
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
 function getArrMaxValue(arr){
    let Max = arr[0];
    for (let i = 1; i < arr.length; i++) {
      if (arr[i] >= Max){
        Max = arr[i];
      }
    }
    return Max;
  }
  let maxP = getArrMaxValue([65,25,65,94,215,435,45])
 document.write(maxP);

</script>

</body>
</html>
返回多個值

return只返回一個值

function fn(x,y){
    let jia = x+y;
    let jian = x-y;
    return [jia , jian];
}

let re = fn(1,2);
document.write(`相加之后的值是${re[0]},相減之后的值是${re[1]}`);

作用域以及作用域鏈

作用域

限定某個名字的可用性的代碼范圍(一個程序代碼中所用到的名字并不是總時有效的和可用的)就是在那個位置起作用

作用域有全局作用域(整個script標簽內(nèi)部)、局部作用域(函數(shù)內(nèi)的代碼環(huán)境)、塊級作用域(由{}包括,if語句和for語句里面的{} 等)

let num = 10;     //全局變量
function fn(){
    console.log(num);
    if(true){
        console.log(num);
    }
}

//=======================
function fn2(){
    let num2 = 20;     //局部變量
    function fn21(){
        let num3 = 30;
    }
    console.log(num3)//報錯
}
console.log(num2);  //報錯

//=======================

if(true){
    let num5 = 50;     //塊級變量
}
consloe.log(num5);     //報錯

坑: 如果在內(nèi)部或者塊級的內(nèi)部直接賦值,則當作全局變量。函數(shù)形參是局部變量。

//一般
let sum = 0;

//
max = 100;    //全局變量
作用域鏈

變量的訪問原則:就近原則,找到最終的值

let num = 10;
function fn(){
    let num = 20;
    console.log(num);    //20
}

匿名函數(shù)

具名函數(shù)

function  fn(){}
fn();

匿名函數(shù)

function(){
  //函數(shù)體
}

// 1種寫法
let num = 10;
let fn = function(){
    console.log(111);
}
fn();

// 2種寫法
let fn2 = function(x, y){
    console.log(x+y);
}
fn2(1,2);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button>點擊我</button>
<script>
//  let btn = document.querySelector('button')
  // btn.onclick = function (){
  //   alert('月薪過萬');
  // }

  let btn = document.querySelector('button')
  btn.addEventListener('click',function (){
    alert('月薪過萬');
  })
</script>

</body>
</html>
立即執(zhí)行函數(shù)

立即執(zhí)行,不用調(diào)用。多個立即執(zhí)行函數(shù)之間必須有分號隔開

(function(){ console.log(11) })()      //方式一

(function(){console.log(11)}())      //方式二
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button>點擊我</button>
<script>
//  let btn = document.querySelector('button')
  // btn.onclick = function (){
  //   alert('月薪過萬');
  // }

//第一個小括號放的是形參,第二個小括號里面放的是實參

(function (){console.log(111);})();
(function (){ console.log(111)}());

(function (x , y){return x+y;})( 1 ,2);

(function (x,y){return x+y;}(1,2));
</script>

</body>
</html>

綜合案例:轉(zhuǎn)換時間

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  let time = +prompt('請輸入秒數(shù)');
  function getTime(time){

    let h = parseInt(time /60 /60 % 24);

    let m = parseInt(time /60 % 60);
    let s = parseInt(time % 60);
    h = h< 10? '0'+h :h;
    m = m< 10? '0'+m :m;
    s = s< 10? '0'+s :s;
    return `${h} 時 ${m} 分 ${s} 秒` ;

  }
  let str = getTime(time);
  document.write(str);
</script>

</body>
</html>
  1. 實參個數(shù)少于形參,返回結(jié)果NaN

  2. 實參個數(shù)多于形參,實際只看形參個數(shù)的多少,剩下的將不被處理

  3. 如果不知道實參個數(shù),可以算數(shù)下面的方式

function fn(){       
                                    //arguments函數(shù)內(nèi)有效 ,表現(xiàn)形式是偽數(shù)組
                                    //偽數(shù)組 比真數(shù)組 少了一些pop push等方法
    console.log(arguments);       //[1,2,3]
    let sum = 0;
    for(let i = 0; i<arrguments.length;i++){
        sum += arguments[i];
    }
    console.log(sum);
}

fn(1,2,3)   //6

函數(shù)傳參賦值小技巧

我怕你傳參不帶參數(shù)

方法一

function fn(x, y){
  x = x || 0;
  y = y || 0;
  console.log(x+y)
}

fn();
fn(1,2)

方法二

function fn(x= 0,fn = 0){
    console.log(x+y)
}

fn()
fn(1,2)    //調(diào)用的時候會進行內(nèi)部替換

對象,面向?qū)ο缶幊?/h2>

啥是對象?

Object:對象也是一種數(shù)據(jù)類型,一種無序的數(shù)據(jù)集合。

對象聲明語法:

ler 對象名 = {
    屬性名: 屬性值
    方法名 : function(){}
}

//例子
let person = {
    uname = 'Barbatos',
    age = '5000',
    sex = 'M',
    sayHi: function(){
        document.write('hi~');
    },
    mtv: function(x){
        console.log(x)
    }
}

//屬性訪問
let uname = person.uname;    //   訪問屬性一     對象名.屬性名
person.sayHi();              //   訪問對象方法
person.mtv('Genshin Impact')   //  訪問對象方法并傳參

let unmae = person['uname']  //   訪問屬性二     對象名['屬性名']

操作和遍歷

增刪查改

改:屬性賦值

對象.屬性 = 值;
對象.方法 = function(){}

增:添加對象屬性(js 可以非常方便的的動態(tài)新增屬性或者方法)

對象.新屬性 = 值;
let person = {
    uname = 'Barbatos',
    age = '5000',
    sex = 'M',
    sayHi: function(){
        document.write('hi~');
    },
    mtv: function(x){
        console.log(x)
    }
}

//改
persion.uname = 'Venti';
persion.sayHi = function(){
    document.write('欸嘿');
}

//新增
person.aName = '賣唱的';
person.move = function(){};
//刪
delete person.aName;
delete person.move;

//對象遍歷
for(let key in person){
    console.log(key)       //屬性名
    console.log(person[key]);   //屬性值 由于unmae = person['uname'],可以把 key 看作是 'uname’
}
對象遍歷
for(let key in 對象){
    //key
    //對象[key]
}

案例:學生信息表

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    table{
        width: 700px;
        text-align: center;
    }

    table,
    th,
    td{
        border: 1px solid #ccc;
        background-color: #1f9763;
    }

    caption{
        font-size: 18px;
        margin-top: 10px;
        font-weight: 700;
    }

    tr{
        height: 40px;
        cursor: pointer;
    }
    table tr:nth-child(1){
        background-color: #1f9763;
    }
    table tr:not(fist-child):hover {
        background-color: #eee;
    }
</style>
<body>
<script>
    //數(shù)組 里面可以存放任何數(shù)據(jù)類型,對象也可以
    //對象數(shù)組
    let students= [
        {name : 'Barbatos', age:4000, gender : 'm' , hometown : 'MD'},
        {name : 'Morax', age:6000, gender : 'm' , hometown : 'LY'},
        {name : 'Beelzebul', age:3000, gender : 'w' , hometown : 'DQ'},
        {name : 'Nahida', age:500, gender : 'w' , hometown : 'XM'},
    ];

    //遍歷數(shù)組

    document.write(`
        <table>
    <caption>學生列表</caption>
    <tr>
        <th>序號</th>
        <th>姓名</th>
        <th>年齡</th>
        <th>性別</th>
        <th>家鄉(xiāng)</th>
    </tr>
    `)

    //打印一個對象,其實都是里面每一個對象都是 里面的的元素
    for (let i = 0; i < students.length; i++) {
        document.write(`
            <tr>
                    <td>${i+1}</td>
        `);
         for (let k in students[i]) {
             document.write(`
                 <td>${students[i][k]}</td>
                 `);

         }

        document.write(`
            </tr>
        `)

    }

document.write(`
    </table>
`)
</script>
<table>
    <caption>學生列表</caption>
    <tr>
        <th>序號</th>
        <th>姓名</th>
        <th>年齡</th>
        <th>性別</th>
        <th>家鄉(xiāng)</th>
    </tr>
    <tr>
        <td>1</td>
        <td>小米</td>
        <td>16</td>
        <td>男</td>
        <td>河北</td>
    </tr>
</table>
</body>
</html>

Math 數(shù)學對象

內(nèi)置對象:JavaScript一般也會有一些封裝好的對象,提供開發(fā)者使用
Math對象

方法:

  • random() 生成0-1之間的隨機數(shù)(不包括0和1)

  • ceil() 向上取整

  • floor() 向下取整

  • max() 找最大數(shù)

  • min() 找最小數(shù)

  • pow(x,y) 冪運算

  • abs() 絕對值

  • round() 就近取整(負值時,-*.5往大取整 -1.5 取-1值, -1.9取-2值 , -1.1 取-1值)

  • 其他方法,百度

console.log(Math.PI) //圓周率 屬性

console.log(Math.random()) //隨機數(shù) 方法

隨機數(shù)

如何隨機數(shù)

生成0-10的隨機數(shù):

Math.floor(Math.random()*10+1);

生成5-10的隨機數(shù)

Math.floor(Math.random()*(5+1)+5);

生成N-M之間的隨機數(shù)

Math.floor(Math.random()*((M - N) + 1 ) + N );
function getRandom(min,max){
    return Math.floor(Math.random()*((max - min)+1) + min);
}

let random = getRandom(1,10);

案例:隨機數(shù)點名

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  let arr = ['Nahida','barbatos','Morax','Beelzebul'];
  function getRandom(min,max){
    return Math.floor(Math.random()*((max - min)+1) + min);
  }

  let random = getRandom(0,3);
  document.write(arr[random]);
  arr.splice(random,1);
  document.write(`<br>`)
  document.write(arr);

</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>

  function getRandom(min,max){
    return Math.floor(Math.random()*((max - min)+1) + min);
  }
  let random = getRandom(1,10);
  while (true){
    let num = +prompt("猜一個數(shù)");
    if (num === random){
      alert('猜正確了');
      document.write(random);
      break;
    }else if (num > random){

      alert(`私密馬賽,猜大了`)
    }else {

      alert('私密馬賽,猜小了')
    }

  }

</script>

</body>
</html>

綜合案例:學成在線

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>學車在線首頁</title>
    <link rel="stylesheet" href="style.css">
    <style>
        * {
                margin: 0;
                padding: 0;
            }
            .w {
                width: 1200px;
                margin: auto;
            }
            body {
                background-color: #f3f5f7;
            }
            li {
                list-style: none;
            }
            a {
                text-decoration: none;
            }
            .clearfix:before,.clearfix:after {
                content:"";
                display:table; 
              }
              .clearfix:after {
                clear:both;
              }
              .clearfix {
                 *zoom:1;
              }   

            .header {
                height: 42px;
                /* background-color: pink; */
                /* 注意此地方會層疊 w 里面的margin */
                margin: 30px auto;
            }
            .logo {
                float: left;
                width: 198px;
                height: 42px;
            }
            .nav {
                float: left;
                margin-left: 60px;
            }
            .nav ul li {
                float: left;
                margin: 0 15px;
            }
            .nav ul li a {
                display: block;
                height: 42px;
                padding: 0 10px;
                line-height: 42px;
                font-size: 18px;
                color: #050505;   
            }
            .nav ul li a:hover {
                border-bottom: 2px solid #00a4ff;
                color: #00a4ff;
            }
            /* search搜索模塊 */
            .search {
                float: left;
                width: 412px;
                height: 42px;
                margin-left: 70px;
            }
            .search input {
                float: left;
                width: 345px;
                height: 40px;
                border: 1px solid #00a4ff;
                border-right: 0;
                color: #bfbfbf;
                font-size: 14px;
                padding-left: 15px;
            }
            .search button {
                float: left;
                width: 50px;
                height: 42px;
                /* 按鈕button默認有個邊框需要我們手動去掉 */
                border: 0;
                background: url(images/btn.png);
            }
            .user {
                float: right;
                line-height: 42px;
                margin-right: 30px;
                font-size: 14px;
                color: #666;
            }
            /* banner區(qū)域 */
            .banner {
                height: 421px;
                background-color: #1c036c;
            }
            .banner .w {
                height: 421px;
                background: url(images/banner2.png) no-repeat top center;
            }
            .subnav {
                float: left;
                width: 190px;
                height: 421px;
                background: rgba(0,0,0, 0.3);
            }
            .subnav ul li {
                height: 45px;
                line-height: 45px;
                padding: 0 20px;
            }
            .subnav ul li a {
                font-size: 14px;
                color: #fff;
            }
            .subnav ul li a span {
                float: right;
            }
            .subnav ul li a:hover {
                color: #00a4ff;
            }
            .course {
                float: right;
                width: 230px;
                height: 300px;
                background-color: #fff;
                /* 浮動的盒子不會有外邊距合并的問題 */
                margin-top: 50px;
            }
            .course h2 {
                height: 48px;
                background-color: #9bceea;
                text-align: center;
                line-height: 48px;
                font-size: 18px;
                color: #fff;
            }
            .bd {
                padding: 0 20px;
            }
            .bd ul li {
                padding: 14px 0;
                border-bottom: 1px solid #ccc;
            }
            .bd ul li h4 {
                font-size: 16px;
                color: #4e4e4e;
            }
            .bd ul li p {
                font-size: 12px;
                color: #a5a5a5;
            }
            .bd .more {
                display: block;
                height: 38px;
                border: 1px solid #00a4ff;
                margin-top: 5px;
                text-align: center;
                line-height: 38px;
                color: #00a4ff;
                font-size: 16px;
                font-weight: 700;
            }
            /* 精品推薦模塊 */
            .goods {
                height: 60px;
                background-color: #fff;
                margin-top: 10px;
                box-shadow: 0 2px 3px 3px rgba(0,0,0, 0.1);
                /* 行高會繼承, 會繼承給3個孩子 */
                line-height: 60px;
            }
            .goods h3 {
                float: left;
                margin-left: 30px;
                font-size: 16px;
                color: #00a4ff;
            }
            .goods ul {
                float: left;
                margin-left: 30px;
            }
            .goods ul li {
                float: left;
            }
            .goods ul li a {
                padding: 0 30px;
                font-size: 16px;
                color: #050505;
                border-left: 1px solid #ccc;
            }
            .mod {
                float: right;
                margin-right: 30px;
                font-size: 14px;
                color: #00a4ff;
            }
            .box {
                margin-top: 30px;
            }
            .box-hd {
                height: 45px;
            }
            .box-hd h3 {
                float: left;
                font-size: 20px;
                color: #494949;
            }
            .box-hd a {
                float: right;
                font-size: 12px;
                color: #a5a5a5;
                margin-top: 10px;
                margin-right: 30px;
            }
            /* 把li 的父親ul 修改的足夠?qū)捯恍心苎b開5個盒子就不會換行了 */
            .box-bd ul {
                width: 1225px;
            }
            .box-bd ul li {
                position: relative;
                top: 0;
                float: left;
                width: 228px;
                height: 270px;
                background-color: #fff;
                margin-right: 15px;
                margin-bottom: 15px;
                transition: all .3s;

            }
            .box-bd ul li:hover {
                top: -8px;
                box-shadow: 2px 2px 2px 2px rgba(0,0,0,.3);
            }
            .box-bd ul li img {
                width: 100%;
            }
            .box-bd ul li h4 {
                margin: 20px 20px 20px 25px;
                font-size: 14px;
                color: #050505;
                font-weight: 400;
            }
            .box-bd .info {
                margin: 0 20px 0 25px;
                font-size: 12px;
                color: #999;
            }
            .box-bd .info span {
                color: #ff7c2d;
            }
            /* footer 模塊 */
            .footer {
                height: 415px;
                background-color: #fff;
            }
            .footer .w {
                padding-top: 35px;
            }
            .copyright {
                float: left;
            }
            .copyright p {
                font-size: 12px;
                color: #666;
                margin: 20px 0 15px 0;
            }
            .copyright .app {
                display: block;
                width: 118px;
                height: 33px;
                border: 1px solid #00a4ff;
                text-align: center;
                line-height: 33px;
                color: #00a4ff;
                font-size: 16px;
            }
            .links {
                float: right;
            }
            .links dl {
                float: left;
                margin-left: 100px;
            }
            .links dl dt {
                font-size: 16px;
                color: #333;
                margin-bottom: 5px;
            }
            .links dl dd a {
                color: #333;
                font-size: 12px;
            }
    </style>
</head>

<body>

    <!-- 4. box核心內(nèi)容區(qū)域開始 -->
    <div class="box w">
        <div class="box-hd">
            <h3>精品推薦</h3>
            <a href="#">查看全部</a>
        </div>
        <div class="box-bd">
            <ul class="clearfix">
                <script>
                    let data = [
                        {
                            src: 'images/course01.png',
                            title: 'Think PHP 5.0 博客系統(tǒng)實戰(zhàn)項目演練',
                            num: 1125
                        },
                        {
                            src: 'images/course02.png',
                            title: 'Android 網(wǎng)絡(luò)動態(tài)圖片加載實戰(zhàn)',
                            num: 357
                        },
                        {
                            src: 'images/course03.png',
                            title: 'Angular2 大前端商城實戰(zhàn)項目演練',
                            num: 22250
                        },
                        {
                            src: 'images/course04.png',
                            title: 'Android APP 實戰(zhàn)項目演練',
                            num: 389
                        },
                        {
                            src: 'images/course05.png',
                            title: 'UGUI 源碼深度分析案例',
                            num: 124
                        },
                        {
                            src: 'images/course06.png',
                            title: 'Kami2首頁界面切換效果實戰(zhàn)演練',
                            num: 432
                        },
                        {
                            src: 'images/course07.png',
                            title: 'UNITY 從入門到精通實戰(zhàn)案例',
                            num: 888
                        },
                        {
                            src: 'images/course08.png',
                            title: '我會變,你呢?',
                            num: 590
                        },
                        {
                            src: 'images/course08.png',
                            title: '我會變,你呢?',
                            num: 590
                        }
                    ]
                    // 根據(jù)數(shù)據(jù)的個數(shù)來渲染 到底有多少個小li 
                    // console.log(data.length)

                    for (let i = 0; i < data.length; i++) {
                        document.write(`
                        <li>
                                <img src="${data[i].src}">
                                <h4>${data[i].title}</h4>
                                <div class="info">
                                    <span>高級</span>  · <span>${data[i].num}</span>人在學習
                                </div>
                        </li>
                   `)
                    }

                </script>

            </ul>
        </div>
    </div>

</body>

</html>

不同數(shù)據(jù)類型的存儲方式

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Map與WeakMap類型在JavaScript中的使用
js內(nèi)置對象的常用屬性和方法(Array | String | Date | Math)
js遇到代碼出現(xiàn)問題時如何調(diào)試代碼
JavaScript詳細解析
JS輸出語句匯總(5種)
document.querySelector()方法
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服