[JS] Arrays 陣列

leo
1 min readFeb 3, 2021

大綱

[1. 陣列的介紹

2. 產生陣列的方法

2.1.1 陣列常值(Array literals) (2020/02/04) done

2.1.2 展開運算子 (2020/02/04) done

2.1.3 建構子 (The Array() constructor)

2.1.3 The Array.of() and Array.from() factory methods

]

  1. JS陣列介紹

MDN 簡介

一種在單個變數名下儲存資料項列表的簡潔方法

什麼是 陣列

陣列通常描述為「像列表的物件」:也就是一個列表物件,裡面含有幾個數值。陣列物件能放在變數裡面,處理方式也與資料型別大致相同。不過主要差異為,陣列可以獨立存取、並高效處理裡面的數值:像是利用迴圈,對每個數值作相同處理。例如我們的陣列是一組有項目和價格的產品、我們可以用迴圈把單價印在發票上、最後在發票底下印出合計。

不用陣列的話,就會需要註冊、並單獨呼叫很多獨立變數。這樣會花更多時間寫程式、效率更低、還更容易寫錯。只有十個的話還好解決,但如果有一百個,甚至一千個呢?我們會在接下來闡述之。

JavaScript大全 介紹

An array is an ordered collection of values. Each value is called an element, and each element has a numeric position in the array, known as its index. JavaScript arrays are untyped: an array element may be of any type, and different elements of the same array may be of different types. Array elements may even be objects or other arrays, which allows you to create complex data structures, such as arrays of objects and arrays of arrays

ES6

ES6 introduces a set of new array classes known collectively as “typed arrays.” Unlike regular JavaScript arrays, typed arrays have a fixed length and a fixed numeric element type. They offer high performance and byte-level access to binary data

2. 產生陣列 Creating Arrays

有以下四種方法

  1. 陣列常值(Array literals)

2. 展開運算子(...) 允許可迭代的陣列(The … spread operator on an iterable object)

3.建構子 (The Array() constructor)

4.The Array.of() and Array.from() factory methods

2.1.1 陣列常值

基本用法

中度用法

進階寫法

陣列中加入物件

可以看到陣列裡面加入兩個陣列,其中各穿插一個物件

陣列逗號用途

[情境1] 留位子

想到班上 一號同學和三號同學共同先進入教室,但二號同學還沒進入教室,所以先幫二號同學留位子.

或是 三個同學都離開教室但椅子還是留在教室

2.1.2 展開運算子 ( The Spread Operator )

ES6 The Spread Operator 用法

In ES6 and later, you can use the “spread operator,” …, to include the elements of one array within an array literal:

代表 陣列中只要是常數,都可以使用… 方法展開

基本用法

這樣代表不需要用 for 迴圈也可以直接展開

那第二個好處是可以複製陣列,且不影響原本的陣列,只做 shallow copy

第三個用處:展開字串

這樣把數字都放在一起

但ES6 要知道 Set()

Set 物件可讓你儲存任何類型的唯一值(unique),不論是基本型別(primitive)值或物件參考(references)。

可以不要字串中重複的值

所以知道Set() 讀取到陣列的 uniqle value

--

--