JavaScript中的數組方法可以通過數組對象來調用。以下是一些常用的數組方法的使用示例:
var fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // 輸出: ["apple", "banana", "orange"]
var fruits = ["apple", "banana", "orange"];
var removedFruit = fruits.pop();
console.log(fruits); // 輸出: ["apple", "banana"]
console.log(removedFruit); // 輸出: "orange"
var fruits = ["apple", "banana", "orange"];
var removedFruit = fruits.shift();
console.log(fruits); // 輸出: ["banana", "orange"]
console.log(removedFruit); // 輸出: "apple"
var fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // 輸出: ["apple", "banana", "orange"]
var fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1); // 從索引1開始刪除1個元素
console.log(fruits); // 輸出: ["apple", "orange"]
fruits.splice(1, 0, "kiwi", "grape"); // 從索引1開始刪除0個元素,并插入新元素
console.log(fruits); // 輸出: ["apple", "kiwi", "grape", "orange"]
var fruits = ["apple", "banana", "orange", "kiwi", "grape"];
var selectedFruits = fruits.slice(1, 4);
console.log(selectedFruits); // 輸出: ["banana", "orange", "kiwi"]
這些只是一些常見的數組方法的使用示例,JavaScript中還有很多其他有用的數組方法,可以根據具體需求查閱文檔。