JavaScript数组常用api方法总结

1.Array.from() 方法 将伪数组转为真实数组

Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。 就是将伪数组转换为真数组来使用真数组中的方法。

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

2. Array.map() 方法  遍历数组返回新的数组

当我们在数组上使用该.map() 方法时, 它都会在原数组基础尚返回一个新的修改本。 该.map() 方法具有循环遍历数组并且修改的功能。.map() 每当您要更新数组中的每一项并且需要返回新数组时, 都可以使用该方法

const cars = ["Porsche", "Audi", "BMW", "Volkswagen"];

const coolCars = cars.map( car => `$ {car}是一个非常酷的汽车品牌!`)
 //结果:[“保时捷是一个非常酷的汽车品牌!”,“ 奥迪是一个非常酷的汽车品牌!”,“ 宝马是一个非常酷的汽车品牌!”,“ 大众汽车是一个非常酷的汽车品牌!”]]

// 用map方法处理数组中的对象
const cars = [{
        brand: "保时捷",
        price: 100000
      },
      {
        brand: "奥迪",
        price: 80000
      }
    ];
    const carsWithPriceAndTax = cars.map(carObject => {
      return {
        // 返回原对象
        ...carObject,
        // 返回新的含税的价格新值
        priceWithTax: carObject.price * 1.2
      }
    });
    // 结果:
    [{
        brand: "保时捷",
        price: 100000,
        priceWithTax: 120000
      },
      {
        brand: "奥迪",
        price: 80000,
        priceWithTax: 96000
      }
    ];

3. Array.filter()设定条件过滤数组

  .filter() 方法允许您根据特定条件获取数组中的项目。 就像该.map() 方法一样会返回一个新数组, 并保持原始数组不变。

const cars = [{
        brand: "保时捷",
        price: 100000
      },
      {
        brand: "奥迪",
        price: 80000
      },
      {
        brand: "丰田",
        price: 30000
      }
    ];
  //  现在, 假设所有价值40, 000 或以上的汽车都非常昂贵  
// 我们可以使用该.filter() 方法以两个不同的数组获取所有“ 便宜” 和“ 昂贵” 的汽车。
    const expensiveCars = cars.filter(car => car.price >= 40000);
    const cheapCars = cars.filter(car => car.price < 40000);
    // 结果 - 昂贵的
    [{
        brand: "保时捷",
        price: 100000
      },
      {
        brand: "奥迪",
        price: 80000
      }
    ];
    // 结果 - 便宜的
    [{
      brand: "丰田",
      price: 30000
    }];

 4. Array.reduce()

.reduce() 方法将回调函数作为其第一个参数,回调函数提供了total和 item参数, 用于执行简单计算。 并将可选的初始值作为其第二个参数。 如果未提供初始值, 则使用第一个数组中的值。如果数组中是普通类型的数据,那么不用给初始值, 如果数组中是引用类型的数据,那么初始值是必须的。

const numbers = [13, 65, 29, 81, 47];
    // 然后, 我们可以使用.reduce() 方法将所有这些值加在一起。

    const total = numbers.reduce((total, item) => total+ item, 0);
    // Result - Total:235

   // 使用该.reduce() 方法的另一种用处是展平数组。 已经有很多方法可以做到这一点, 这就是其中一种。

    const flattened = [
      [0, 1],
      [2, 3],
      [4, 5]
    ].reduce(
      (total, item) => total.concat(item),
      []
    )
    // Result - Flattened: [0, 1, 2, 3, 4, 5]

5 Array.forEach() 遍历数组每一个元素修改

.forEach() 方法非常类似于常规 for 循环。

它遍历一个数组并在每个项目上执行一个函数。

.forEach() 的第一个参数是一个回调函数,其中包括循环的当前值和索引(item,index)。

使用场景:当只想遍历任何数组的每个项目而无需构造新数组时。

const cars = [
  {brand: "保时捷", price: 100000},
  {brand: "奥迪", price: 80000},
  {brand: "丰田", price: 30000}
];

// 我们可以遍历所有内容,并 console.log 打印包含汽车品牌和价格的句子

cars.forEach(car => {
  console.log(`The ${car.brand} will cost you ${car.price} before taxes`);
});
// Result:
"The 保时捷 will cost you 100000 before taxes"
"The 奥迪 will cost you 80000 before taxes"
"The 丰田 will cost you 30000 before taxes"

6. Array.find()遍历数组找第一个匹配的条件

.find() 方法看起来与 .filter() 很类似

就像.filter()方法一样,您可以传入数组符合条件的判断

两者之间的区别是,.find() 仅返回与您提供的条件匹配的第一个元素。

使用汽车示例,让我们使用该 .find() 方法获得数组中遇到的第一辆昂贵的汽车。

何时使用Array.find()?

当需要获取通过显式定义的测试的数组的第一项时

const cars = [
  {brand: "Porsche", price: 100000},
  {brand: "Audi", price: 80000},
  {brand: "Toyota", price: 30000}
];
// 获取价格超过40000的汽车
const expensiveCar = cars.find(car => car.price >= 40000);
// find方法只返回满足条件的第一个元素
{brand: "Porsche", price: 100000}

7. Array.every()遍历数组 所有元素 是否满足返回布尔值

.every()方法将检查数组中的每个元素是否通过提供的条件。

如果数组中的所有元素都符合条件,则该方法将返回 true。如果没有,它将返回 false

例如,我们可以使用该方法检查过去5年内是否制造了所有汽车。

const cars = [
  {brand: "Porsche", price: 100000, builtIn: 2018},
  {brand: "Audi", price: 80000, builtIn: 2019},
  {brand: "Toyota", price: 30000, builtIn: 2019}
];

const productYears = cars.every(car => car.builtIn >= 2016);
// becaue eyeryone's bulidIn>2016,so we can get true.
true

8. Array.some()遍历数组是否满足条件返回布尔值(不是遍历所有元素只要有一个满足就返回true)

.some() 方法与方法.every()类似,但是如果数组中的所有元素都通过测试,则返回 true,而不是如果数组中的至少一个元素通过测试,则返回 true 。 如果该 .some() 方法找到成功的数组元素,它将停止并返回 true。否则返回 false

让我们再次使用汽车数组,但是这次我们将检查某些汽车是否超过5年。

const cars = [
  {brand: "Porsche", price: 100000, builtIn: 2018},
  {brand: "Audi", price: 80000, builtIn: 2019},
  {brand: "Toyota", price: 30000, builtIn: 2019}
];
const carsOlderThanFiveYears = cars.some(car => car.builtIn < 2016);
// because eyery car's years Older than 5 Years,so we get false
false

9.Array.push()从后面添加数组元素

将一个或多个元素添加到数组的末尾,并返回该数组的新长度。参数就是要添加的元素

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

10,Array.unshift ()从头添加数组元素

方法将一个或多个元素添加到数组的开头,并返回该数组的新长度

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]

11. Array.splice()依据下标添加和删除数组元素

方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。第一个参数是要删除元素的下标,第二个参数是从该位置开始要删除元素的个数,第三个参数是从该位置要添加的元素

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 0, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

12.Array.slice ()依据下标截取并浅复制数组元素

slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

当参数为正时,参数的绝对值是按数组从前往后算的下标来截取,当只有一个参数时会默认截取到最后一个值;第一个和第二个参数是数组的下标值来看要被截取的范围,(begin,end)end下标的元素不被截取。

当参数为负时,参数的绝对值是按数组从后往前算的下标来截取,当只有一个参数时会默认截取到最后一个值;第一个和第二个参数是数组的下标值来看要被截取的范围,(begin,end)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"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(0, -3));
// expected output: Array ["camel", "duck"]

13.Array.pop()删除数组最后一个元素

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"]

plants.pop();

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

14.Array.reverse() 翻转数组

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"]

15.Array.concat()连接两个数组

 concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

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"]

16.Array.sort()给数组从小到大排序

sort() 方法用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的

由于它取决于具体实现,因此无法保证排序的时间和空间复杂性。

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

const array1 = [10,2,4,5888888,8,6];
array1.sort();
console.log(array1);
// expected output: Array [10, 2, 4, 5888888, 6, 8]

17.Array.includes()找元素返回布尔值

includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

18.Array.indexOf()找元素返回索引

indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

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

19.Array.fill()填充数组

fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

20Array.flat()深度遍历展开数组

参数: depth(可选): 提取嵌套数组的结构深度,默认为1。

返回值:展开后的新数组。flat方法会移除数组中的空白项若不清楚有多少层嵌套,可以直接用 Infinity 设置,就可全部展开Infinity 正无穷大的数值。

{
        let arr = [1,2,[3,[4,[5]]],6]
        let one = arr.flat()
        console.log(one)//[1, 2, 3, Array(2), 6]
 
        let inf = arr.flat(Infinity)
        console.log(inf)//[1, 2, 3, 4, 5, 6]
    }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值