登录
首页 >  文章 >  前端

JS 中使用哪种数组方法?

来源:dev.to

时间:2024-10-05 17:27:34 287浏览 收藏

本篇文章给大家分享《JS 中使用哪种数组方法?》,覆盖了文章的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

JS 中使用哪种数组方法?

  1. 要改变原始数组:
    1. 推() 说明: 将一个或多个元素添加到数组末尾。
js
const fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits); // output: ['apple', 'banana', 'orange']
  1. 流行() 描述:从数组中删除最后一个元素并返回该元素。
js
const fruits = ['apple', 'banana', 'orange'];
const lastfruit = fruits.pop();
console.log(fruits); // output: ['apple', 'banana']
console.log(lastfruit); // output: 'orange'
  1. 移位() 描述:从数组中删除第一个元素并返回该元素。
js
const fruits = ['apple', 'banana', 'orange'];
const firstfruit = fruits.shift();
console.log(fruits); // output: ['banana', 'orange']
console.log(firstfruit); // output: 'apple'
  1. 取消移位() 说明: 将一个或多个元素添加到数组的开头。
js
const fruits = ['banana', 'orange'];
fruits.unshift('apple');
console.log(fruits); // output: ['apple', 'banana', 'orange']
  1. 拼接() 描述:通过删除或替换现有元素和/或添加新元素来更改数组的内容。
js
const fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1, 'kiwi', 'mango'); // removes 1 element at index 1 and adds 'kiwi' and 'mango'
console.log(fruits); // output: ['apple', 'kiwi', 'mango', 'orange']
  1. 填充() 描述:用静态值填充数组中从起始索引到结束索引的所有元素。
js
const numbers = [1, 2, 3, 4, 5];
numbers.fill(0, 1, 4); // fills from index 1 to 4 with 0
console.log(numbers); // output: [1, 0, 0, 0, 5]
  1. 排序() 描述:对数组的元素进行就地排序并返回排序后的数组。
js
const numbers = [5, 3, 8, 1];
numbers.sort(); // sorts numbers as strings by default
console.log(numbers); // output: [1, 3, 5, 8]
  1. 反向() 描述:原地反转数组的元素。
js
const numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers); // output: [4, 3, 2, 1]
  1. splice() 用于移除 描述:您还可以使用 splice() 删除元素而不添加任何元素。
js
const fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1); // removes 1 element at index 1
console.log(fruits); // output: ['apple', 'orange']
  1. copywithin() 描述:浅拷贝数组的一部分到同一数组中的另一个位置并更改原始数组。
js
const numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3); // Copies elements from 
index 3 to 0
console.log(numbers); // Output: [4, 5, 3, 4, 5]

终于介绍完啦!小伙伴们,这篇关于《JS 中使用哪种数组方法?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>