目錄
- Javascript 常用的Array方法--溫習一下
- 前言
- 常用的 Array 方法
- Array.from()
- Array.isArray()
- Array.of()
- Array.concat()
- Array.every()
- Array.filter()
- Array.find()
- Array.findIndex()
- Array.forEach()
- Array.includes()
- Array.indexOf()
- Array.join()
- Array.lastIndexOf()
- Array.map()
- Array.pop()
- Array.push()
- Array.reverse()
- Array.shift()
- Array.slice()
- Array.some()
- Array.sort()
- Array.splice()
- Array.unshift()
Javascript 常用的Array方法–溫習一下
前言
2018年已經過去,在過去的一年中大部分的時間都用在了 coding 業務代碼和各種生活瑣事中,花在 learning 的時間少之又少,2019已經來了,在這裏先立個 flag :
- review 自己之前寫的代碼,在欠缺的地方做改進。
- 重溫CSS、JS基礎。
- 完成自己的前端框架(一定完成·一定完成·一定完成)重要的事情說三遍,已經拖了太久了。
- 完成個人博客網站(越寫越覺得自己是個重度拖延症患者(O.O)…)。
- 早睡、早起、少擼、多看書。---------(少擼:指玩遊戲,想歪的自己面壁)
- 深入學習各大框架底層。
flag 就立這麼多吧!不然沒法實現了。
先來看看JS
常用的 Array 方法
Array.from()
Array.from() 方法從一個類似數組或可迭代對象中創建一個新的數組實例。
String 轉換 Array
/*
* params form(arrayLike, Fn?, thisArg?)
* arrayLike: 想要轉換成數組的僞數組對象或可迭代對象。
* Fn: 可選,如果指定了該函數,arrayLike中每個元素都會執行該函數
* thisArg: 可選,Fn中this的指向對象,使用該參數時Fn不能使用箭頭函數,否則this無法指向設置的對象
**/
console.log(Array.from('hello world'));
// ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
Set 轉換 Array
const set = new Set(['hello world', window]);
Array.from(set); // ['hello world', window]
Map 轉換 Array
const maps = new Map([[1, 3], [5, 7], [2, 4]]);
Array.from(maps); // [[1, 3], [5, 7], [2, 4]
Array.form() 配合 Set 使數組去重合並
function combine() {
let arr = [].concat.apply([], arguments); //沒有去重複的新數組
return Array.from(new Set(arr));
}
var m = [1, 2, 2], n = [2,3,3];
console.log(combine(m,n)); // [1, 2, 3]
Array.isArray()
用於確定傳遞的值是否是一個 Array。
/*
* params isArray(obj)
* obj: 想要轉換成數組的僞數組對象或可迭代對象。
**/
// 假如不存在 Array.isArray(obj),則在其他代碼之前運行下面的代碼將創建該方法。
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
Array.of()
Array.of() 方法創建一個具有可變數量參數的新數組實例,而不考慮參數的數量或類型。
/*
* params of(ele1, ele2, ele3···)
* eleN: 任意個參數,將按順序輸出爲數組並返回。
**/
Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]
如果原生不支持的話,在其他代碼之前執行以下代碼會創建 Array.of() 。
if (!Array.of) {
Array.of = function() {
return Array.prototype.slice.call(arguments);
};
}
Array.concat()
concat() 方法用於合併兩個或多個數組。此方法不會更改現有數組,而是返回一個新數組。
/*
* params arr1.concat(arr2, arr3, arr4···)
* arrN: 任意個參數,將按順序合併後輸出爲新數組。
**/
var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];
console.log(array1.concat(array2)); // ['a', 'b', 'c', 'd', 'e', 'f']
Array.every()
every() 方法測試數組的所有元素是否都通過了指定函數的測試。
/*
* params every(fn, thisArg?)
* fn: array中每個元素都會執行的函數測試。
* thisArg: 可選,fn中this的指向對象,使用該參數時fn不能使用箭頭函數,否則this無法指向thisArg
**/
function isBelowThreshold(currentValue) {
return currentValue < 40;
}
var array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
// ES6
const array2 = [1, 30, 39, 29, 10, 13];
console.log(array2.every(item => item < 40));
Array.filter()
filter() 方法創建一個新數組, 其包含通過所提供函數實現的測試的所有元素。
/*
* params every(callback, thisArg?)
* callback: array中每個元素都會執行的函數測試。
* thisArg: 可選,callback中this的指向對象,使用該參數時callback不能使用箭頭函數,否則this無法指向thisArg
**/
unction isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
//ES6
const filtered2 = [12, 5, 8, 130, 44].filter(item => item >= 10);
查詢篩選對象數組
// ES6
const array = [{a: 1, b:2}, {a: 1, b:2}, {a: 2, b:2}, {a: 2, b:3}, {a: 1, b:2}];
console.log(array.filter(item => item.a === 2))
// [{a: 2, b: 2}, {a: 2, b: 3}]
console.log(array.filter(item => {
return item.a === 2;
}))
// 兩個寫法是一樣的,寫法1是省略了return,寫法2中必須有return。
Array.find()
find() 方法返回數組中滿足提供的測試函數的第一個元素的值。否則返回 undefined。
用對象的屬性查找數組裏的對象
const array1 = [{a: 1, b:2}, {a: 1, b:2}, {a: 2, b:2}, {a: 1, b:2}, {a: 1, b:2}];
console.log(array1.find(item => item.a === 2));
// Object { a: 2, b: 2 }
Array.findIndex()
findIndex()方法返回數組中滿足提供的測試函數的第一個元素的索引。否則返回-1。
使用方法和 Array.find() 一樣,差別僅爲返回值是索引。這裏就不多說了
Array.forEach()
forEach() 方法對數組的每個元素執行一次提供的函數。
const array1 = ['a', 'b', 'c'];
array1.forEach((el, i) => {
console.log(el, i)
})
// a, 0
// b, 1
// c, 2
Array.includes()
includes() 方法用來判斷一個數組是否包含一個指定的值,根據情況,如果包含則返回 true,否則返回false。
var pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
var array1 = [1, {a: 1}, 3];
console.log(array1.includes({a: 1}));
// expected output: false
var o = {a: 1}
var array1 = [1, o, 3];
console.log(array1.includes(o));
// expected output: true
Array.indexOf()
indexOf()方法返回在數組中可以找到一個給定元素的第一個索引,如果不存在,則返回-1。
var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
Array.join()
join() 方法將一個數組(或一個類數組對象)的所有元素連接成一個字符串並返回這個字符串。
默認使用’ , ’
var elements = ['Fire', 'Wind', 'Rain'];
console.log(elements.join());
// expected output: Fire,Wind,Rain
console.log(elements.join(''));
// expected output: FireWindRain
console.log(elements.join('-'));
// expected output: Fire-Wind-Rain
Array.lastIndexOf()
lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或變量)在數組中的最後一個的索引,如果不存在則返回 -1。從數組的後面向前查找,從 fromIndex 處開始。
var animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
console.log(animals.lastIndexOf('Dodo'));
// expected output: 3
console.log(animals.lastIndexOf('Tiger'));
// expected output: 1
Array.map()
map() 方法創建一個新數組,其結果是該數組中的每個元素都調用一個提供的函數後返回的結果。
// ES6
const arr1 = [1, 2, 3, 4];
const arr2 = arr1.map(item => item * item)
console.log(arr2)
// [1, 4, 9, 16]
Array.pop()
pop()方法從數組中刪除最後一個元素,並返回該元素的值。此方法會更改原始數組的長度。
var plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// expected output: "tomato"
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
Array.push()
push() 方法將一個或多個元素添加到數組的末尾,並返回該數組的新長度。
var animals = ['pigs', 'goats', 'sheep'];
console.log(animals.push('cows'));
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]
Array.reverse()
reverse() 方法將數組中元素的位置顛倒。
var array1 = ['one', 'two', 'three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']
var reversed = array1.reverse();
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']
Array.shift()
shift() 方法從數組中刪除第一個元素,並返回該元素的值。此方法更改數組的長度。
var array1 = [1, 2, 3];
var firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
Array.slice()
slice() 方法返回一個新的數組對象,這一對象是一個由 begin和 end(不包括end)決定的原數組的淺拷貝。原始數組不會被改變。
var 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"]
Array.some()
some() 方法測試是否至少有一個元素通過由提供的函數實現的測試。
const array = [1, 2, 3, 4, 5];
console.log(array.some(item => item % 2 === 0));
// expected output: true
Array.sort()
sort() 方法用原地算法對數組的元素進行排序,並返回數組。排序算法現在是穩定的。默認排序順序是根據字符串Unicode碼點。
// 默認排序
var array1 = [1, 30, 4, 21];
array1.sort();
console.log(array1);
// expected output: Array [1, 21, 30, 4]
// 比較數字而非字符串,比較函數可以簡單的以 a 減 b,如下的函數將會將數組升序排列
var numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
// [1, 2, 3, 4, 5]
Array.splice()
splice()方法通過刪除現有元素和/或添加新元素來修改數組,並以數組返回原數組中被修改的內容。
/*
* params splice(start, deleteCount, item1?,item2?···)
* start: 指定要修改的起始位置。
* deleteCount: 要刪除的元素個數。(爲0時不刪除,該情況下item至少存在一個)
* item[N]: 要添加到數組的元素
*/
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at 1st index position
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']
Array.unshift()
unshift() 方法將一個或多個元素添加到數組的開頭,並返回該數組的新長度。
var array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// expected output: 5
console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
先寫那麼多,慢慢完善······