在 JavaScript 中,数组 是一种特殊类型的对象,用于存储有序的数据集合。数组可以保存不同数据类型的多个值,包括数字、字符串、对象,甚至其他数组。
创建数组最常见的方法是使用方括号 []。
示例:
const fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
此方法创建一个空数组或具有指定元素的数组。
示例:
const numbers = new Array(5); // Creates an array with 5 empty slots console.log(numbers.length); // Output: 5 const colors = new Array("Red", "Green", "Blue"); console.log(colors); // Output: ["Red", "Green", "Blue"]
使用从零开始的索引访问数组元素。
示例:
const fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
const numbers = new Array(5); // Creates an array with 5 empty slots console.log(numbers.length); // Output: 5 const colors = new Array("Red", "Green", "Blue"); console.log(colors); // Output: ["Red", "Green", "Blue"]
const fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits[0]); // Output: Apple console.log(fruits[2]); // Output: Cherry
fruits[1] = "Blueberry"; console.log(fruits); // Output: ["Apple", "Blueberry", "Cherry"]
fruits.push("Mango"); console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Mango"]
fruits.pop(); console.log(fruits); // Output: ["Apple", "Banana"]
fruits.unshift("Strawberry"); console.log(fruits); // Output: ["Strawberry", "Apple", "Banana"]
fruits.shift(); console.log(fruits); // Output: ["Apple", "Banana"]
console.log(fruits.indexOf("Banana")); // Output: 1
console.log(fruits.includes("Cherry")); // Output: false
const numbers = [1, 2, 3]; const squared = numbers.map((num) => num ** 2); console.log(squared); // Output: [1, 4, 9]
const evenNumbers = numbers.filter((num) => num % 2 === 0); console.log(evenNumbers); // Output: [2]
const sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // Output: 6
const moreFruits = ["Peach", "Grape"]; const allFruits = fruits.concat(moreFruits); console.log(allFruits); // Output: ["Apple", "Banana", "Peach", "Grape"]
const sliced = allFruits.slice(1, 3); console.log(sliced); // Output: ["Banana", "Peach"]
allFruits.splice(1, 1, "Orange"); console.log(allFruits); // Output: ["Apple", "Orange", "Peach", "Grape"]
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }
数组可以包含其他数组,创建矩阵或多维结构。
示例:
for (let fruit of fruits) { console.log(fruit); }
fruits.forEach((fruit) => console.log(fruit));
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; console.log(matrix[1][2]); // Output: 6
解构允许您将数组中的值提取到变量中。
示例:
const fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
嗨,我是 Abhay Singh Kathayat!
我是一名全栈开发人员,拥有前端和后端技术方面的专业知识。我使用各种编程语言和框架来构建高效、可扩展且用户友好的应用程序。
请随时通过我的商务电子邮件与我联系:kaashshorts28@gmail.com。
以上是理解 JavaScript 中的数组的详细内容。更多信息请关注PHP中文网其他相关文章!