首頁  >  文章  >  web前端  >  JS 中使用哪一種數組方法?

JS 中使用哪一種數組方法?

DDD
DDD原創
2024-09-20 18:45:39781瀏覽

Which Array method to use in 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 中使用哪一種數組方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn