Featured image of post 【JavaScript 變數】變數類型介紹:Array 陣列

【JavaScript 變數】變數類型介紹:Array 陣列

【JavaScript 變數】變數類型介紹:Array 陣列

Photo by Mohammad Rahmani on Unsplash

函式資料

變數 說明
Array.forEach() 輪詢陣列資料
Array.map() 輪詢陣列資料,運算後建立新陣列
Array.filter() 過濾符合條件數值
Array.reduce() 收攏陣列數值
Array.fill() 填入指定數值
Array.isArray() 判斷是否為陣列
Array.indexOf() 判斷資料第一次出現在陣列哪個索引值內,找不到則回傳 -1
Array.lastIndexOf() 判斷資料最後一次出現在陣列哪個索引值內,找不到則回傳 -1
Array.join() 合併陣列資料
Array.sort() 排序陣列資料
Array.pop() 移除陣列最後一筆資料,到指定變數
Array.push() 將資料加入陣列中,加到陣列後方
Array.shift() 移除陣列第一筆資料,到指定變數
Array.unshift() 將資料加入陣列中,加到陣列前方
Array.slice() 切割陣列資料
Array.splice() 移除指定陣列位置資料,並插入新的資料到指定位置中
Array.toString() 轉換成字串
Array.values() 取得陣列所有數值
Array.find() 找尋第一筆符合條件資料,並回傳該資料
Array.findIndex() 找尋第一筆符合條件資料,並回傳該資料索引
Array.includes() 是否包含指定資料
Array.flat() 陣列降維
Array.flatMap() 陣列降維 + map
Array.concat() 連接陣列(複製陣列)
Array.reverse() 反轉陣列
Array.from() 迭代陣列資料進行運算,然後建立新陣列

Array.forEach() 輪詢陣列資料

const Employee = ['Kay', 'Jay', 'KJ'];

//  直接輪詢列印資料
// Kay
// Jay
// KJ
Employee.forEach(currentValue => console.log(currentValue));


// 取得輪詢資料及鍵值
Employee.forEach((currentValue, index, originalArray) => {
    // index 0, currentValue: Kay
    // index 1, currentValue: Jay
    // index 2, currentValue: KJ
    console.log(`index ${index}, currentValue: ${currentValue}`);
});

Array.map() 輪詢陣列資料,運算後建立新陣列

const OriginalArray = [1, 4, 9, 16];

// pass a function to map
const MapArray = OriginalArray.map(x => x * 3);

// [ 1, 4, 9, 16 ]
console.log(OriginalArray);
// [ 3, 12, 27, 48 ]
console.log(MapArray);
const Employee = ['Kay', 'Jay', 'KJ'];

// 取得輪詢資料及鍵值
const NewEmployee = Employee.map((currentValue, index, originalArray) => {
    // index 0, currentValue: Kay
    // index 1, currentValue: Jay
    // index 2, currentValue: KJ
    let valueMapResult = `${currentValue} (${currentValue.length})`;
    return valueMapResult;
});

// [ 'Kay', 'Jay', 'KJ' ]
console.log(Employee);
// [ 'Kay (3)', 'Jay (3)', 'KJ (2)' ]
console.log(NewEmployee);

Array.sort() 排序陣列資料

Array.prototype.sort() - JavaScript | MDN

如果沒有 callback 排序函式,則預設的排序順序是根據字串的 Unicode 編碼位置(code points) 而定

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
// ["Dec", "Feb", "Jan", "March"]
console.log(months);

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
// [1, 100000, 21, 30, 4]
console.log(array1);

傳入比較的兩個變數 a, b

狀況 回傳值
a 要排前面 -1,或負值
b 要排前面 1,或正值
a 與 b 順序不變 0

按照數字大小排序

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
// [1, 2, 3, 4, 5]
console.log(numbers);
var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// 排序數字大小
items.sort(function (a, b) {
    if (a.value < b.value) {
        // a 比較小,排前面
        return -1;
    } else if (a.value > b.value){
        // b 比較小,排前面
        return 1;
    } else {
        // 一樣大,不調整位置
        return 0;
    }
});


items.sort(function (a, b) {
  return a.value - b.value;
});

// [
//   { name: 'The', value: -12 },
//   { name: 'Magnetic', value: 13 },
//   { name: 'Edward', value: 21 },
//   { name: 'Sharpe', value: 37 },
//   { name: 'Zeros', value: 37 },
//   { name: 'And', value: 45 }
// ]
console.log(items);

按照字母大小排序

var items = [
    { name: 'Edward', value: 21 },
    { name: 'Sharpe', value: 37 },
    { name: 'And', value: 45 },
    { name: 'The', value: -12 },
    { name: 'Magnetic', value: 13 },
    { name: 'Zeros', value: 37 }
];

// 依照名稱字母順序排序
items.sort(function(a, b) {
    var nameA = a.name.toUpperCase(); // ignore upper and lowercase
    var nameB = b.name.toUpperCase(); // ignore upper and lowercase
    if (nameA < nameB) {
        // nameA 字母順序比較低,排前面
        return -1;
    }
    if (nameA > nameB) {
        // nameB 字母順序比較低,排前面
        return 1;
    }

    // nameA 與 nameB 字母順序一樣(同樣字串),不調整排序
    return 0;
});

// [
//   { name: 'And', value: 45 },
//   { name: 'Edward', value: 21 },
//   { name: 'Magnetic', value: 13 },
//   { name: 'Sharpe', value: 37 },
//   { name: 'The', value: -12 },
//   { name: 'Zeros', value: 37 }
// ]
console.log(items);

Array.fill() 填入指定數值

初始化陣列並給予預設值

let newArray = new Array(256).fill(0);

Array.filter() 過濾符合條件數值

const Employee = ['Kay', 'Jay', 'KJ'];

// 取得輪詢資料及鍵值
const NewFilterEmployee = Employee.filter((currentValue, index, originalArray) => {
    if (currentValue.length >= 3) {
        // 搜集符合條件的資料
        return true;
    } else {
        // 丟棄不符條件的資料
        return false;
    }
});

// [ 'Kay', 'Jay', 'KJ' ]
console.log(Employee);
// [ 'Kay', 'Jay' ]
console.log(NewFilterEmployee);

Array.reduce() 收攏陣列數值

const OriginalArray = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = OriginalArray.reduce(
    // 陣列資料加總
    (previousValue, currentValue) => previousValue + currentValue,
    initialValue
);

console.log(sumWithInitial);
// expected output: 10
const Employee = ['Kay', 'Jay', 'KJ'];

let accumulatorString = '';
// 取得輪詢資料及鍵值
const NewReduceEmployee = Employee.reduce((accumulator, currentValue, currentIndex, originalArray) => {
    // accumulator :  | currentValue : Kay
    // accumulator :  ,Kay  | currentValue : Jay
    // accumulator :  ,Kay  ,Jay  | currentValue : KJ
    console.log(`accumulator : ${accumulator} | currentValue : ${currentValue}`);
    // reduce 資料 = 累計資料 + , + 現有資料
    let reduceValue = `${accumulator} ,${currentValue} `;
    return reduceValue;
}, accumulatorString);

// '' 空字串
console.log(accumulatorString);
// [ 'Kay', 'Jay', 'KJ' ]
console.log(Employee);
//  ,Kay  ,Jay  ,KJ
console.log(NewReduceEmployee);

Array.find() 找尋第一筆符合條件資料,並回傳該資料

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

Array.findIndex() 找尋第一筆符合條件資料,並回傳該資料索引

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

Array.includes() 是否包含指定資料

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

Array.includes() 與 Array.indexOf() 比較

console.log([1,2,3].includes(1))
// true
console.log([1,2,3].indexOf(1))
// 0
console.log([1,2,NaN].includes(NaN))
// true(這邊includes找得出Nan)
console.log([1,2,NaN].indexOf(NaN))
// -1(但indexOf找不到)

Array.flat() 陣列降維

陣列降維並去除空資料

const Employee = [
    'Kay', 'Jay',
    [],
    ['KJ'],
];

let flatEmployee = Employee.flat();

// [ 'Kay', 'Jay', [], [ 'KJ' ] ]
console.log(Employee);

// 陣列降維並去除空資料
// [ 'Kay', 'Jay', 'KJ' ]
console.log(flatEmployee);

重複降維

const Employee = [
    [
        ['Kay', 'Jay'],
        ['Engineer', 'CTO'],
    ]
];

let flat1Employee = Employee.flat();
let flat2Employee = flat1Employee.flat();

// [ [ [ 'Kay', 'Jay' ], [ 'Engineer', 'CTO' ] ] ]                                                        22:51:47
console.log(Employee);

// 降維 1 次
// [ [ 'Kay', 'Jay' ], [ 'Engineer', 'CTO' ] ]
console.log(flat1Employee);

// 降維 2 次
// [ 'Kay', 'Jay', 'Engineer', 'CTO' ]
console.log(flat2Employee);

Array.concat() 連接陣列(複製陣列)

連接陣列

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

使用 concat 複製陣列

let Employee = ['Kay', 'Jay'];
let NewEmployee = Employee.concat();
NewEmployee.push('KJ');

// [ 'Kay', 'Jay' ]
console.log(Employee);
// [ 'Kay', 'Jay', 'KJ' ]
console.log(NewEmployee);

Array.slice() 切割陣列資料

切割陣列資料

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

使用 slice 複製陣列

let Employee = ['Kay', 'Jay'];
let NewEmployee = Employee.slice();
NewEmployee.push('KJ');

// [ 'Kay', 'Jay' ]
console.log(Employee);
// [ 'Kay', 'Jay', 'KJ' ]
console.log(NewEmployee);

Array.reduce() 收攏陣列數值

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce( (previousValue, currentValue) => {
        return previousValue + currentValue;
    },
    initialValue
);

console.log(sumWithInitial);
// expected output: 10

Array.splice() 移除指定陣列位置資料,並插入新的資料到指定位置中

僅移除陣列資料

let Employee = ['Kay', 'Jay', 'KJ'];

// [ 'Kay', 'Jay', 'KJ' ]
console.log(Employee);

// 使用 Array.splice() 刪除陣列元素
Employee.splice(1, 1);

// [ 'Kay', 'KJ' ]
console.log(Employee);

// 2:陣列資料剩餘 2 筆
console.log(Employee.length);

移除陣列資料,並插入新資料到指定位置

let Employee = ['Kay', 'Jay', 'KJ'];
let AddEmployee = ['Apple', 'Banana'];

// [ 'Kay', 'Jay', 'KJ' ]
console.log(Employee);

// 使用 Array.splice() 刪除陣列元素,並插入資料
Employee.splice(1, 1, ...AddEmployee);

// [ 'Kay', 'Apple', 'Banana', 'KJ' ]
console.log(Employee);

僅插入資料

let Employee = ['Kay', 'Jay', 'KJ'];
let AddEmployee = ['Apple', 'Banana'];

// [ 'Kay', 'Jay', 'KJ' ]
console.log(Employee);

// 使用 Array.splice() 插入資料
Employee.splice(1, 0, ...AddEmployee);

// [ 'Kay', 'Apple', 'Banana', 'Jay', 'KJ' ]
console.log(Employee);

複製陣列

let Employee = ['Kay', 'Jay'];
let CopyEmployee = [...Employee];

// [ 'Kay', 'Jay' ]
console.log(Employee);
// [ 'Kay', 'Jay' ]
console.log(CopyEmployee);

插入陣列資料

let Employee = ['Kay', 'Jay'];
let OtherEmployee = ['Alex', ...Employee, 'Carl'];

// [ 'Kay', 'Jay' ]
console.log(Employee);
// [ 'Alex', 'Kay', 'Jay', 'Carl' ]
console.log(OtherEmployee);
let Employee = ['Kay', 'Jay'];
let OtherEmployee = ['Alex', 'Carl'];
let NewEmployee = [...Employee, ...OtherEmployee];

// [ 'Kay', 'Jay' ]
console.log(Employee);
// [ 'Alex', 'Carl' ]
console.log(OtherEmployee);
// [ 'Kay', 'Jay', 'Alex', 'Carl' ]
console.log(NewEmployee);

Reference

Donate KJ 贊助作者喝咖啡

如果這篇文章對你有幫助的話,可以透過下面支付方式贊助作者喝咖啡,如果有什麼建議或想說的話可以贊助並留言給我
If this article has been helpful to you, you can support the author by treating them to a coffee through the payment options below. If you have any suggestions or comments, feel free to sponsor and leave a message for me!
方式 Method 贊助 Donate
PayPal https://paypal.me/kejyun
綠界 ECPay https://p.ecpay.com.tw/AC218F1
歐付寶 OPay https://payment.opay.tw/Broadcaster/Donate/BD2BD896029F2155041C8C8FAED3A6F8
All rights reserved,未經允許不得隨意轉載
Built with Hugo
Theme Stack designed by Jimmy