DAY 10
1
Modern Web

陣列 Array

陣列的使用

• 立即給值
``````const arr = [1, 2, 3]
console.log(arr.length) // 3
``````
• 後續給值
``````const arr = []
arr[0] = 1
arr[1] = 2
arr[2] = 3
console.log(arr.length) // 3
``````

``````const call = (...arr) => {
console.log(arr); // [ 1, 2, 3 ]
};
call(1, 2, 3);
``````

物件 Object

``````const dog = {
name: 'Tom',
breed: 'Golden Retriever',
weight: 60
}
``````

如何存取物件內的值

``````console.log(dog.breed) // Golden Retriever
console.log(dog["breed"]) // Golden Retriever
``````

物件使用 forEach 方法

``````const dog = {
name: 'Tom',
breed: 'Golden Retriever',
weight: 60
};
Object.keys(dog).forEach((key) => {
console.log(dog[key]);
});

輸出：
// Tom
// Golden Retriever
// 60
``````

物件夾帶方法

``````const dog = {
name: 'Tom',
breed: 'Golden Retriever',
weight: 60,
breaks() {
console.log('woof');
}
};
dog.breaks(); // woof
``````

• 符號都是三個點(...)(free dots)
• 都是在陣列值運算
• 一個是展開陣列中的值，一個是集合其餘的值成為陣列

展開運算子

• Used to split up array element or object poperties
• 簡單來說像是陣列與物件的變數繼承
``````// 陣列展開用法
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4];

console.log(newNumbers);
``````

output: [1, 2, 3, 4]

``````// 物件展開用法
const person = {
name: 'Andy',
};
const newPerson = {
...person,
age: 21,
};

console.log(newPerson);
``````

output: { name: 'Andy', age: 21 }

其餘運算符

• 其餘運算符(Rest Operator)
• Used to merge a list of function arguments into an array
• 雖然與展開運算子特性的符號是一模一樣的，都是三個點(...)，但使用的情況與意義不同

Array.filter()方法會過濾陣列的元素，並將通過測試的元素傳回成為一個新陣列。
Array.filter()方法使用回呼函式來對元素進行過濾，須由設計師自行撰寫過濾程式。

``````// Array.filter() 過濾陣列元素
const filter = (...args) => args.filter(el => el === 2);

console.log(filter(1, 2, 3));
``````

output: [ 2 ]

Destructuring Assignment (解構賦值)

• Easily extract array elements or object properties and store them in variables

• 解構解構允許你拉出單個元素或屬性，並將他們儲存在數組的變數中

• Array Destructuring

``````const numbers = [1, 2, 3];
const [num1, num2] = numbers;

console.log(num1, num2);
``````

Reference and Primitive Types

• 變數參數傳值(passed by value)
``````let num1 = 1;
const num2 = num1;
num1 = 2;

console.log(num1, num2);
``````

output: 2 1

• 物件傳址(passed by reference)
``````const person = {
name: 'Andy'
};
const secondPerson = person;

person.name = 'Tank';

console.log(secondPerson);
``````

output: { name: 'Tank' }

``````const person = {
name: 'Andy'
};
const secondPerson = {
...person
};

person.name = 'Tank';

console.log(secondPerson);
``````

output: { name: 'Andy' }

1 則留言

0
Cheng®
iT邦新手 5 級 ‧ 2020-01-16 14:45:41

`console.log(dog[breed]) // Golden Retriever`

console.log(dog["breed"])

Cheng® 對！感謝勘誤～ 單、雙引號都行！