網頁全端開發JavaScript_0925

陣列 array


  • 陣列array裡的值稱為元素element
  • 陣列中的元素可以增加或減少,JavaScript中陣列可以包含不同資料類型
  • 查詢元素時跟字串相同,用非負整數0123來查詢

let array = ["grace", "mike" ,false ,3.14, null, undefined ];
console.log( array [ 3] );
結果為 3.14


換掉第~個值

let array = ["grace", "mike" ,false ,3.14, null, undefined ];
array [ 0 ] = "wilson";
console.log( array [ 0] );
結果為 "wilson"



資料型別 JavaScript data type


原始型別 Primitive type

JS 的資料型別分成兩大類:「原始型別、物件型別」
1 Number 數字
2 String 字串
3 Boolean 布林值
4 undefined 未被賦值的變數
5 null 不存在的值、空值
6 symbol 符號
7 BigInt 任意長度的整數

物件型別 Object type

原始型別以外,其他的值都是物件型別
1 Function 函式
2 Array 陣列
3 Object 物件
4 Date
5 Map
6 Set

原始型別

  • 原始型別的值是 pass by value
  • 儲存以及複製的都是「值本身」,互不影響
  • JS 中,原始值是無法改變的
    我們可以給變數重新賦予一個「新值」,但不能去修改「原本的值」

let a = "hello"
a.toUpperCase ()
console.log (a) // 依然是 hello
a = a.toUpperCase ()
console.log (a) // 得到 HELLO


let people1 = "wilson" ;
let people2 = people1;

people1 = "Joy"; // 更改 people1 的值
console.log(people2); // people2 是一個獨立的新值, 結果是"wilson"



物件型別

  • 物件型別的值是 pass by reference 引用數據類型
  • 賦值時是指向同個地址的概念
  • 更改值時,會連帶影響到其他指向同地址的變數

let fruit1 = ["apple", "grape", "lemon"]
let fruit2 = fruit1
fruit2[0] = "banana" // 更改 fruit2 的值
console.log (fruit1)
console.log (fruit2)
結果為
"banana", "grape", "lemon"
"banana", "grape", "lemon"

*更改fruit2 的值,fruit1的值也會被更改



比較 Reference Data Type


let arr1 = [ 1 ,2 ,3 ];
let arr2 = [ 1 ,2 ,3 ] ;
console.log (arr1 === arr2)
結果為false

let arr1 = [ 1 ,2 ,3 ];
let arr2 = arr1 ;
console.log (arr1 === arr2)
結果為true


.length查詢陣列長度

let arr1 = [ 1 ,2 ,3 ];
console.log (arr1.length);
結果為3

.push (element)從陣列尾端「新增」1個或多個元素,並return陣列新長度

.pop( )刪除陣列最後1個值,並回傳該值

.shift( )刪除陣列第1個值,並回傳該值

.unshift (element)從陣列開頭「新增」1個或多個元素,並return陣列新長度