Zi 字媒體
2017-07-25T20:27:27+00:00
Array prototype Introduction
ECMAScript:6
在 Javascript 中,Array instances 是繼承自 Array.prototype。
以下就介紹幾個常見的,由 Array.prototype 提供的陣列操作方法。
find()、findIndex()
find() 與 findIndex() 通常用在尋找陣列中的值。
範例
let itemArr = [
{
item: 'Pork',
price: '100'
},
{
item: 'Beef',
price: '200'
},
{
item: 'Apple',
price: '10'
}
];
// Find array Index
let index = itemArr.findIndex(function (element) {
return element.price == 10;
});
// Find array Index with ES6
let indexES6 = itemArr.findIndex(element => element.price == 10);
// Find array value with ES6
// 若條件不符,會回傳 undefined
let item = itemArr.find(element => element.price == 10);
sort()、reverse()
sort() 是用來進行陣列的排序。
Notice: sort() 的排序順序是根據字串的 Unicode 編碼位置。
範例
// Sort array
let nameArr = ['Mag', 'Johnson', 'Febr'];
// [ 'Febr', 'Johnson', 'Mag' ]
nameArr.sort();
// 排序順序是根據字串的 Unicode 編碼位置
let numArr = [12, 3, 5, 53, 12, 53, 47];
// [ 12, 12, 3, 47, 5, 53, 53 ]
numArr.sort();
// 透過Compare function 設定條件(ascending sort)
// [ 3, 5, 12, 12, 47, 53, 53 ]
numArr.sort(function (a, b) {
// 設定條件,當 a > b 時才會進行交換
return a - b;
});
// ES6 (descending sort)
numArr.sort((a, b) => b - a);
let itemArr = [
{
item: 'Pork',
price: '100'
},
{
item: 'Beef',
price: '200'
},
{
item: 'Apple',
price: '10'
}
];
// 針對 Object 排序
itemArr.sort((a, b) => a.price > b.price ? 1 : -1);
// Reverse
numArr.reverse();
splice()
splice() 是用來控制陣列元素的去留。
範例
let months = ['Jan', 'March', 'April', 'June'];
// 加入 Feb 在 1 的位置
// [ 'Jan', 'Feb', 'March', 'April', 'June' ]
months.splice(1, 0, 'Feb');
// 把 June 取代成 May
// [ 'Jan', 'Feb', 'March', 'April', 'May' ]
months.splice(4, 1, 'May');
// 從 1 開始往後刪除 4 筆資料
// [ 'Jan' ]
months.splice(1, 4);
filter()
filter() 方法是直接根據條件產生一個新的陣列。
範例
let words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
let result = words.filter(function (word) {
return word.length > 6;
});
// ES6
let resultES6 = words.filter(word => word.length > 6);
map()、reduce()
map() 會走訪陣列中每一個元素,將元素根據你的條件進行處理再回傳新的集合。
reduce() 會代入一個計數器和陣列的每個元素,根據你的條件進行處理再回傳最後結果。
範例
// Map
let arr = [1, 4, 9, 16];
// 所有數值乘以 2
let map1 = arr.map(item => item * 2);
// 只有 index 0 的數字乘以 2
let map2 = arr.map((item, index) => {
return index === 0 ? item * 2 : item;
});
// Reduce
let arr2 = [1, 2, 3, 4];
let result = arr2.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
});
Categories: JavaScript
Tags: javascript
分類
Android
AngularJS
API Blueprint
Chrome
Database
MySQL
DataStructure
Docker
Editor
Vim
Firefox
Git
GitLab
Google API
Hadoop
Language
Go
Java
JavaScript
jQuery
jQueryChart
Node.js
Vue
PHP
Laravel
ZendFramework
Python
Mac
Network
Cisco
DLink
Juniper
Oauth
Server
Apache
Share
Unix
FreeBSD
Linux
WebDesign
Bootstrap
CSS
HTML
Wordpress
Search
搜尋關鍵字:
寫了
5860316篇文章,獲得
23313次喜歡