首页 >web前端 >js教程 >Which Array method to use in JS?

Which Array method to use in JS?

DDD
DDD原创
2024-09-20 18:45:39952浏览

Which Array method to use in JS?

  1. To mutate the original Array:
    1. push() Description: Adds one or more elements to the end of an array.
js
const fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits); // Output: ['apple', 'banana', 'orange']
  1. pop() Description: Removes the last element from an array and returns that element.
js
const fruits = ['apple', 'banana', 'orange'];
const lastFruit = fruits.pop();
console.log(fruits); // Output: ['apple', 'banana']
console.log(lastFruit); // Output: 'orange'
  1. shift() Description: Removes the first element from an array and returns that element.
js
const fruits = ['apple', 'banana', 'orange'];
const firstFruit = fruits.shift();
console.log(fruits); // Output: ['banana', 'orange']
console.log(firstFruit); // Output: 'apple'
  1. unshift() Description: Adds one or more elements to the beginning of an array.
js
const fruits = ['banana', 'orange'];
fruits.unshift('apple');
console.log(fruits); // Output: ['apple', 'banana', 'orange']
  1. splice() Description: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.
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. fill() Description: Fills all the elements of an array from a start index to an end index with a static value.
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. sort() Description: Sorts the elements of an array in place and returns the sorted array.
js
const numbers = [5, 3, 8, 1];
numbers.sort(); // Sorts numbers as strings by default
console.log(numbers); // Output: [1, 3, 5, 8]
  1. reverse() Description: Reverses the elements of an array in place.
js
const numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers); // Output: [4, 3, 2, 1]
  1. splice() for Removal Description: You can also use splice() to remove elements without adding any.
js
const fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1); // Removes 1 element at index 1
console.log(fruits); // Output: ['apple', 'orange']
  1. copyWithin() Description: Shallow copies part of an array to another location in the same array and changes the original array.
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]

以上是Which Array method to use in JS?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn