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() 排序阵列资料
如果没有 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
- Array - JavaScript | MDN - English
- Array - JavaScript | MDN - 中文
- JS 深拷贝与浅拷贝 | Explosion Units
- JS reduce 使用 | Explosion Units
- JS reduce 使用 | Explosion Units
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 |