一、字面量方式
1. 說明:
// 語法: // [element0, element1, ..., elementN] // 示例: const fruits = ['apple', 'banana', 'orange'];
2. 解釋:
字面量方式是JavaScript中創建數組最常見的方式,利用方括號將數組元素括起來並用逗號分隔,可以在創建數組時直接添加元素。
3. 應用:
// 訪問數組元素 console.log(fruits[0]); // 返回apple console.log(fruits[1]); // 返回banana // 改變數組元素 fruits[1] = 'grape'; console.log(fruits); // 返回["apple", "grape", "orange"] // 添加數組元素 fruits.push('watermelon'); console.log(fruits); // 返回["apple", "grape", "orange", "watermelon"] // 刪除數組元素 fruits.pop(); console.log(fruits); // 返回["apple", "grape", "orange"]
二、構造函數方式
1. 說明:
// 語法: // new Array(element0, element1, ..., elementN) // 或 // new Array(length) // 示例: const nums1 = new Array(1, 2, 3); const nums2 = new Array(4);
2. 解釋:
構造函數方式是JavaScript中創建數組的另一種方式。可以使用new運算符和Array()構造函數來創建數組,其中參數可以是元素列表或表示數組長度的數字。如果只傳遞一個參數,則該參數指定數組的長度。
3. 應用:
// 訪問數組元素 console.log(nums1[0]); // 返回1 console.log(nums1[1]); // 返回2 // 獲取數組長度 console.log(nums1.length); // 返回3 // 添加數組元素 nums1[3] = 4; console.log(nums1); // 返回[1, 2, 3, 4] // 刪除數組元素 delete nums1[2]; console.log(nums1); // 返回[1, 2, empty, 4] console.log(nums1[2]); // 返回undefined console.log(nums1.length); // 返回4(長度未變)
三、Array.from()靜態方法
1. 說明:
// 語法: // Array.from(arrayLike[, mapFn[, thisArg]]) // 示例: const str = 'hello world'; const chars = Array.from(str);
2. 解釋:
Array.from()是在ES6中引入的靜態方法,用於從類似數組或可迭代對象中創建新的數組實例。第一個參數是數組模板,第二個參數是一個映射函數,可以對元素進行轉換,第三個參數是函數執行時的上下文對象。
3. 應用:
// 訪問數組元素 console.log(chars[0]); // 返回h console.log(chars[1]); // 返回e // 轉換數組元素 const nums = Array.from(nums1, x => x * 2); console.log(nums); // 返回[2, 4, NaN, 8] // 過濾數組元素 const odds = Array.from(nums1, x => (x % 2 !== 0) ? x : undefined).filter(Boolean); console.log(odds); // 返回[1]
四、擴展運算符方式
1. 說明:
// 語法: // [...array] // 示例: const arr1 = [1, 2]; const arr2 = [3, 4]; const arr3 = [...arr1, ...arr2];
2. 解釋:
擴展運算符是在ES6中引入的新語法,用於將一個可迭代對象展開到一個新的數組中。可以用於合併數組、將字符串轉為數組等。
3. 應用:
// 查看數組元素 console.log([...str]); // 返回["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"] // 合併數組 console.log(arr3); // 返回[1, 2, 3, 4] // 簡單克隆數組 const arr4 = [...arr1]; console.log(arr4); // 返回[1, 2] // 將字符串轉換為數組 console.log([...str]); // 返回["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
五、TypedArray方式
1. 說明:
// 語法: // new TypedArray(length) // 示例: const nums3 = new Int32Array(3);
2. 解釋:
TypedArray是在ES6中引入的新的數據類型,指的是一種原始的二進制數據類型,可以存儲在數組緩衝區中。創建一個TypedArray時需要指定數組的長度,同時也可以在創建時向數組中賦初始值,這種方式不同於數組字面量方式,因為數組字面量的元素類型是根據值來確定的,而TypedArray的元素類型是由數組類型來確定的。
3. 應用:
// 修改數組元素 nums3[0] = 1; nums3[1] = 2; nums3[2] = 3; console.log(nums3); // 返回[1, 2, 3] // 獲取數據長度和數據類型 console.log(nums3.length); // 返回3 console.log(nums3.constructor.name); // 返回Int32Array
六、總結
數組是在JavaScript編程中非常常見的數據結構,對於不同的使用場景和需求,選擇合適的創建方式可以使代碼更具可讀性和清晰度。字面量方式是最常見的一種數組創建方式,但是當我們需要在運行時擴展數組長度時,用構造函數或擴展運算符等方式是比較方便的選擇。對於需要存儲二進制數據,TypedArray是一個更加高效的方式。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/196857.html