JavaScript数组方法

1.数组去重
一种是实用.from()方法, 第二种是es6的扩展运算符...

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

2.替换或修改数组中的值
可用使用.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.清空数组

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

//方式2:给数组的length赋值为0
var arr = [1,2,3,4];  
   arr.length = 0;

//方式3:直接赋予新数组 []
var arr = [1,2,3,4];  
   arr = [];

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

4.数组转对象
数组转换为对象的最快方法是使用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.合并数组
除了使用.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.求数组的交集

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.从数组中删除虚值
虚值有false, 0, „”, null, NaN, undefined。从数组中删除此类值。可使用.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. 从数组中获取随机值
    可以根据数组长度获取随机索引号
var colors = [“blue”, “white”, “green”, “navy”, “pink”, “purple”, “orange”, “yellow”, “black”, “brown”];

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

9.反转数组

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()方法
查找给定元素的最后一次出现的索引。

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.对数组中的所有值求和

var nums = [1, 5, 2, 6];
var sum = nums.reduce((x, y) => x + y);
console.log(sum); // returns 14

你可能感兴趣的:(JavaScript数组方法)