分享20個Javascript中的數組方法,收藏

什麼是數組?與其他編程語言中的數組一樣,Array對象允許在一個變量名稱下存儲多個項的集合,並且具有用於執行常見數組操作的成員。

 

聲明數組

我們可以用兩種不同的方式聲明數組。

使用新陣列

使用new Array,我們可以指定希望存在於數組中的元素,如下所示:

const fruits = new Array('Apple', 'Banana');
console.log(fruits.length);

數組文字表示法

使用數組文本聲明,我們指定數組將具有的值。如果我們不聲明任何值,數組將爲空。

// 'fruits' array created using array literal notation.
const fruits = ['Apple', 'Banana'];
console.log(fruits.length);

Javascript數組方法

下面是Array對象的方法列表及其說明。

1.forEach

forEach()方法爲每個數組元素執行一次提供的函數。

array.forEach(callback[, thisObject]);

forEach()按索引升序爲數組中的每個元素調用一次提供的callbackFn函數。對於已刪除或未初始化的索引屬性,不會調用它。

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

2.map

該Array.map()方法允許您循環訪問數組並使用回調函數修改其元素。然後將對數組的每個元素執行回調函數。

array.map(callback[, thisObject]);
let arr = [3, 4, 5, 6];

let modifiedArr = arr.map(function(element){
   return element *3;
});

console.log(modifiedArr); // [9, 12, 15, 18]

該Array.map()方法通常用於對元素應用某些更改,無論是像上面的代碼中那樣乘以特定的數字,還是執行應用程序可能需要的任何其他操作。

3.concat

在JavaScript中,concat()是一個字符串方法,用於將字符串連接在一起。concat()方法將一個或多個字符串值附加到調用字符串,然後將連接結果作爲新字符串返回。因爲concat()方法是String對象的方法,所以必須通過String類的特定實例調用它。

array.concat(value1, value2, ..., valueN);
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"]

4.push

Javascript數組push()方法將給定的元素追加到數組的最後,並返回新數組的長度。當您想在數組末尾添加元素時,請使用push()。

array.push(element1, ..., elementN);

 

const countries = ["Nigeria", "Ghana", "Rwanda"];

countries.push("Kenya");

console.log(countries); // ["Nigeria","Ghana","Rwanda","Kenya"]

5.pop

pop()方法從數組中移除最後一個元素,並將該值返回給調用方。如果對空數組調用pop(),它將返回undefined。

Array.prototype.shift()的行爲與pop()類似,但應用於數組中的第一個元素。

array.pop();
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

6.splice

splice()方法是一種通用方法,用於通過在數組的指定位置刪除、替換或添加元素來更改數組的內容。本節將介紹如何使用此方法將元素添加到特定位置。

array.splice(index, howMany, [element1][, ..., elementN]);
const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.splice(2, 0, "Lemon", "Kiwi"); //Banana,Orange,Lemon,Kiwi,Apple,Mango

7.slice

slice()方法將數組的一部分的淺副本返回到從頭到尾(不包括end)選擇的新數組對象中,其中start和end表示該數組中項的索引。原始陣列不會被修改。

array.slice( begin [,end] );
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"]

8.shift

shift()是一個內置的JavaScript函數,用於從數組中刪除第一個元素。shift()函數直接修改您正在使用的JavaScript數組。shift()返回從數組中移除的項。

函數的作用是:刪除索引位置0處的項,並將未來索引號處的值下移一位。

array.shift();
const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

9.unshift

unshift()方法將給定值插入到類似數組的對象的開頭。

push()的行爲與unshift()類似,但應用於數組的末尾。

array.unshift( element1, ..., elementN );
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

10.join

JavaScript數組join()是一個內置方法,它通過連接數組的所有元素來創建並返回新字符串。join()方法將數組中的項連接到字符串中並返回該字符串。指定的分隔符將分隔元素數組。默認分隔符爲逗號(,)。

array.join(separator);
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

11.every

 

every()方法測試數組中的所有元素是否通過所提供函數實現的測試。它返回一個布爾值。

array.every(callback[, thisObject]);
const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

12.filter

filter()方法創建給定數組的一部分的淺副本,過濾掉給定數組中通過所提供函數實現的測試的元素。

array.filter(callback[, thisObject]);
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

13.indexOf

indexOf()方法返回給定元素在數組中的第一個索引,如果不存在,則返回-1。

array.indexOf(searchElement[, fromIndex]);
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

14.reduce

reduce()方法對數組的每個元素執行用戶提供的“reducer”回調函數,依次傳入前一個元素計算的返回值。在數組的所有元素上運行reducer的最終結果是單個值。

array.reduce(callback[, initialValue]);
const array1 = [1, 2, 3, 4];

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

console.log(sumWithInitial)

15.reverse

reverse()方法在原處反轉數組並返回對同一數組的引用,第一個數組元素現在變爲最後一個,最後一個數組元素變爲第一個。換句話說,陣列中的元素順序將轉向與前述相反的方向。

array.reverse();
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

16.sort

sort()方法對數組中的元素進行排序,並返回對已排序的同一數組的引用。默認的排序順序是升序,它是在將元素轉換爲字符串,然後比較它們的UTF-16代碼單元值序列的基礎上構建的。

array.sort( compareFunction );
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

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

17.toString

toString()方法返回表示對象的字符串。

array.toString();
function Dog(name) {
  this.name = name;
}

const dog1 = new Dog('Gabby');

Dog.prototype.toString = function dogToString() {
  return `${this.name}`;
};

console.log(dog1.toString());
// expected output: "Gabby"

18.at

at()方法接受一個整數值並返回該索引處的項,允許使用正整數和負整數。負整數從數組中的最後一項開始倒數。

array.at(index)
const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// expected output: "Using an index of 2 the item returned is 8"

index = -2;

console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// expected output: "Using an index of -2 item returned is 130"

19.find

find()方法返回所提供的數組中滿足所提供的測試函數的第一個元素。如果沒有值滿足測試函數,則返回undefined。

array.find(function(currentValue, index, arr),thisValue)
const array1 = [5, 12, 8, 130, 44];

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

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

20.some

some()方法測試數組中是否至少有一個元素通過了所提供函數實現的測試。如果在數組中找到一個元素,所提供的函數爲該元素返回true,則返回true;否則返回假。它不會修改數組。

array.some(callback[, thisObject]);
const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

 

你學會了嗎?如果對你有幫助,記得點贊支持!如果你正在學習JS或者已經在我們的三十天計劃中完成了4個綜合項目實戰,那不妨可以聽下這個課程體系,三十天計劃羣裏還提供了算法、數組等知識體系!

 

 

 

前端工程師成長方法

更多完整 JavaScript 課程體系在我們的系統班裏有完整的呈現,包含了 JavaScript 基礎篇、重點、算法、原理、面試題、實戰案例講解!同時也爲你提供了前端高級工程師成長體系!(詳細看下圖內容)

 

如果需要深度學習的同學可以聯繫助理老師瞭解詳細的課程以及課程的報名方式!(不定期會推出活動,有大額優惠券推出,活動詳情聯繫助理老師瞭解即可!)如果你纔開始學習前端,那麼可以先學習我們的三十天計劃(零基礎的同學報名系統班同學可以和老師溝通制定學習計劃,可以得到更快的成長!)

 

爲幫助到一部分同學不走彎路,真正達到一線互聯網大廠前端項目研發要求,首次實力寵粉,打造了《30 天挑戰學習計劃》,內容如下:

HTML/HTML5,CSS/CSS3,JavaScript,真實企業項目開發,雲服務器部署上線,從入門到精通

  • PC 端項目開發(1 個)
  • 移動 WebApp 開發(2 個)
  • 多端響應式開發(1 個)

共 4 大完整的項目開發 !一行一行代碼帶領實踐開發,實際企業開發怎麼做我們就是怎麼做。從學習一開始就進入工作狀態,省得浪費時間。

從學習一開始就同步使用 Git 進行項目代碼的版本的管理,Markdown 記錄學習筆記,包括真實大廠項目的開發標準和設計規範,命名規範,項目代碼規範,SEO 優化規範

從藍湖 UI 設計稿 到 PC 端,移動端,多端響應式開發項目開發

  • 真機調試,雲服務部署上線;
  • Linux 環境下 的 Nginx 部署,Nginx 性能優化;
  • Gzip 壓縮,HTTPS 加密協議,域名服務器備案,解析;
  • 企業項目域名跳轉的終極解決方案,多網站、多系統部署;
  • 使用 使用 Git 在線項目部署;

這些內容在《30 天挑戰學習計劃》中每一個細節都有講到,包含視頻 + 圖文教程 + 項目資料素材等。只爲實力寵粉,真正一次掌握企業項目開發必備技能,不走彎路 !

過程中【不涉及】任何費用和利益,非誠勿擾 。

如果你沒有添加助理老師微信,可以添加下方微信,說明要參加 30 天挑戰學習計劃,來自博客園!老師會邀請你進入學習,並給你發放相關資料。

30 天挑戰學習計劃 Web 前端從入門到實戰 | arry老師的博客-艾編程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章