今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

Array in JavaScript

Pranay Rebeyro 2026年07月15日 23:44 0 次阅读 来源:Dev.to

Array An Array is a collection of multiple values stored in a single variable. let fruits = [ " Apple " , " Mango " , " Orange " ]; Here, fruits contains three values. Why Do We Need Arrays? Without an array, you would write: let fruit1 = " Apple " ; let fruit2 = " Mango " ; let fruit3 = " Orange " ; Using an array: let fruits = [ " Apple " , " Mango " , " Orange " ]; This makes the code shorter and easier to manage. Array Index Each value in an array has an index. The index always starts from 0. Index: 0 1 2 ------------------------- Array: Apple Mango Orange Accessing Array Elements Use the index number to access a value. let fruits = [ " Apple " , " Mango " , " Orange " ]; console . log ( fruits [ 0 ]); console . log ( fruits [ 1 ]); // Output: Apple Mango Changing an Array Element You can update any value using its index. let fruits = [ " Apple " , " Mango " , " Orange " ]; fruits [ 1 ] = " Banana " ; console . log ( fruits ); // Output: [ " Apple " , " Banana " , " Orange " ] Finding the Length of an Array Use the "length" property. let fruits = [ " Apple " , " Mango " , " Orange " ]; console . log ( fruits . length ); // Output: 3 Adding Elements push() – Add at the End let fruits = [ " Apple " , " Mango " ]; fruits . push ( " Orange " ); console . log ( fruits ); // Output: ["Apple", "Mango", "Orange"] unshift() – Add at the Beginning let fruits = [ " Mango " , " Orange " ]; fruits . unshift ( " Apple " ); console . log ( fruits ); // Output: ["Apple", "Mango", "Orange"] Removing Elements pop() – Remove from the End let fruits = [ " Apple " , " Mango " , " Orange " ]; fruits . pop (); console . log ( fruits ); // Output: ["Apple", "Mango"] shift() – Remove from the Beginning let fruits = [ " Apple " , " Mango " , " Orange " ]; fruits . shift (); console . log ( fruits ); // Output: ["Mango", "Orange"] Looping Through an Array Use a "for loop" to print all elements. let fruits = [ " Apple " , " Mango " , " Orange " ]; for ( let i = 0 ; i < fruits . length ; i

本文内容来源于互联网,版权归原作者所有
查看原文