JavaScript數(shù)組方法

1.數(shù)組去重
一種是實用.from()方法, 第二種是es6的擴展運算符...

let  fruits = ["banana", "apple", "orange", "apple", "orange", "grape", "apple"]
// 第一種方法
let uniFruits = Array.from(new Set(fruits))
//第二種方法
let uniFruits2 = [...new Set(fruits)]

2.替換或修改數(shù)組中的值
可用使用.splice(start, value to remove, valueToAdd)

let  fruits = ["banana", "apple", "orange", "watermelon", "apple", "orange", "grape", "apple"]
fruits.splice(0, 2, "potato", "tomato")
console.log(fruits) // returns  ["potato", "tomato", "orange", "watermelon", "apple", "orange", "grape", "apple"]

3.清空數(shù)組

//方式1:splice函數(shù)
var arr = [1,2,3,4];  
   arr.splice(0,arr.length); 

//方式2:給數(shù)組的length賦值為0
var arr = [1,2,3,4];  
   arr.length = 0;

//方式3:直接賦予新數(shù)組 []
var arr = [1,2,3,4];  
   arr = [];

//方式4:利用遍歷
var arr = [1,2,3,4]; 
while(arr .length >0){
    arr .pop();}

4.數(shù)組轉對象
數(shù)組轉換為對象的最快方法是使用es6的擴展運算符...

let fruits = ["banana", "apple", "orange", "watermelon"];

let fruitsObj = {...fruits};

console.log(fruitsObj) // returns {0: “banana”, 1: “apple”, 2: “orange”, 3: “watermelon”, 4: “apple”, 5: “orange”, 6: “grape”, 7: “apple”}

5.合并數(shù)組
除了使用.concat()方法,我們也可以使用擴展運算符...。

var fruits = [“apple”, “banana”, “orange”];
var meat = [“poultry”, “beef”, “fish”];
var vegetables = [“potato”, “tomato”, “cucumber”];
var food = […fruits, …meat, …vegetables];
console.log(food); // [“apple”, “banana”, “orange”, “poultry”, “beef”, “fish”, “potato”, “tomato”, “cucumber”]

6.求數(shù)組的交集

var numOne = [0, 2, 4, 6, 8, 8];
var numTwo = [1, 2, 3, 4, 5, 6];
var duplicatedValues = [...new Set(numOne)].filter(item=> numTwo.includes(item))
console.log(duplicatedValues); // returns [2, 4, 6]

7.從數(shù)組中刪除虛值
虛值有false, 0, ?”, null, NaN, undefined。從數(shù)組中刪除此類值??墒褂?filter()方法。

var mixedArr = [0, “blue”, “”, NaN, 9, true, undefined, “white”, false];
var trueArr = mixedArr.filter(Boolean);
console.log(trueArr); // returns [“blue”, 9, true, “white”]

  1. 從數(shù)組中獲取隨機值
    可以根據(jù)數(shù)組長度獲取隨機索引號
var colors = [“blue”, “white”, “green”, “navy”, “pink”, “purple”, “orange”, “yellow”, “black”, “brown”];

var randomColor = colors[(Math.floor(Math.random() * (color.length)))]

9.反轉數(shù)組

var colors = [“blue”, “white”, “green”, “navy”, “pink”, “purple”, “orange”, “yellow”, “black”, “brown”];
var reversedColors = colors.reverse();
console.log(reversedColors); // returns [“brown”, “black”, “yellow”, “orange”, “purple”, “pink”, “navy”, “green”, “white”, “blue”]

10.lastIndexOf()方法
查找給定元素的最后一次出現(xiàn)的索引。

var nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7];
var lastIndex = nums.lastIndexOf(5);
console.log(lastIndex); // returns 9

11.對數(shù)組中的所有值求和

var nums = [1, 5, 2, 6];
var sum = nums.reduce((x, y) => x + y);
console.log(sum); // returns 14
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容