【前端芝士樹】Array的屬性及方法整理(參照MDN)

本文主要是我自己對Array的一些整理,參考自MDN

/**
 * Array 的一些方法
 *  */

const arr = ["1", "2", "3", "four", "hello"];
let arrObj = new Array();

// 屬性
console.log(arr.length); //5
console.log(arr.__proto__);

/**
 * 增刪改查 && 基礎功能
 */
// 增刪改
arr.shift(); //刪除數組的第一個元素
arr.pop(); //刪除數組的最後一個元素
arr.unshift(); //在數組的開頭一個或多個元素,
arr.push(); //在數組的末尾增加一個或者多個元素
[1, 2, 3].concat([6, 7, 8]); //數組合並 [1,2,3,6,7,8]
[1, 2, 3, 4, 5].copyWithin(0, 1, 2); // 淺複製一部分,[2,2,3,4,5], arr.copyWithin(target[, start[, end]])
// splice(start, deleteCount, item) 刪除或者替換現有元素,返回被修改或者刪除的部分
[1, 2, 3].splice(1, 0, "hello"); // [] 原數組變成了[1, 'hello', 2, 3]

// 查找
[1, 2, 3, 4, 5, 6].find(item => item > 3); // 返回複合條件的第一個值 4
[1, 2, 3, 4, 5, 6].findIndex(item => item > 3); // 返回複合條件的第一個值的位置索引 3
[1, 2, 3, 4, 5, 6].includes(3); // 判斷數組是否包含一個指定的值 true
[1, 2, 3, 4, 5, 6].includes(7); // false
[1, 2, 3, 4, 5, 6].indexOf(3); // 判斷數組是否包含一個指定的值 2
[1, 2, 3, 4, 5, 6].indexOf(7); // -1
[1, 2, 3, 4, 5, 6].lastIndexOf(3); // 從後往前找 2
[1, 2, 3, 4, 5, 6].lastIndexOf(7); // -1

// 遍歷所有的元素
[1, 2, 3, 4, 5, 6].forEach(item => console.log(item)); //1,2,3,4,5,6

// 填充數組
[1, 2, 3, 4, 5, 6].fill(0, 1); //[1, 0, 0, 0, 0, 0]
[1, 2, 3, 4, 5, 6].fill(); //[0, 0, 0, 0, 0, 0]

// 過濾數組
[1, 2, 3, 4, 5, 6].filter(item => {
  return item > 3;
}); // [4,5,6]

// 排序 原地歸併算法 穩定 nlog(n)
[1, 3, 4, 2].sort(); // 默認從小到大 [1, 2, 3, 4]

/**
 * 測試
 */
[1, 30, 39, 29, 10, 13].every(currentValue => {
  return currentValue < 40;
}); // arr.every() 測試數組的所有元素是否是通過了指定函數 true
[1, 30, 39, 29, 10, 13].some(curr => curr < 2); // 測試是否至少有一個元素通過測試 true

/**
 * 轉換 && 返回新的對象
 */
[1, 2, 3, 4, 5, 6].join("-"); // 數組轉爲字符串 "1-2-3-4-5-6"
[1, 2, 3].toString(); // 轉換爲字符串,相當於join(','); "1,2,3"
[1, 2, 3].map(item => item * 2); // 映射器 [2, 4, 6]
[1, 2, 3].reduce((acc, curr) => {
  return acc + curr;
}); // 累加器 從左到右 6
[1, 2, 3].reverse(); // 翻轉數組 [3, 2, 1]
[1, 2, 3].slice(1, 2); // 從原數組中選取值,返回新數組 slice(begin, end) [2]
const keys = ["a", "b", "c"].keys(); // 返回每個索引鍵的 Array Iterator {} 對象
for (let key of keys) {
  console.log(key); // expected output: 0 1 2
} // 0 1 2
const values = ["a", "b", "c"].values(); // 返回每個索引鍵的 Array Iterator {} 對象
for (const value of values) {
  console.log(value); // expected output: "a" "b" "c"
}

/**
 * 實驗中的功能 IE和Edge不支持
 *  */
// flat(depth) 展開嵌套數組
[1, 2, [3, 4, [5, 6]]].flat(); // [1, 2, 3, 4, [5, 6]]
[1, 2, [3, 4, [5, 6]]].flat(2); // [1, 2, 3, 4, 5, 6]
[1, 2, [3, 4, [5, 6]]].flat(Infinity); // [1, 2, 3, 4, 5, 6]

// 其他
const arr2 = Array.of(1, 2, 3); // [1,2,3]

const iter = ["a", "b", "c"].entries(); // 返回一個Array Iterator
iter.next().value; // [0, "a"]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章