卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章79230本站已运行4412

JS 中使用哪种数组方法?

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]
卓越飞翔博客
上一篇: 获得全栈开发认证的最快方法
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏