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

JavaScript Arrays Methods - Part 1

Annapoorani Kadhiravan 2026年06月26日 11:33 2 次阅读 来源:Dev.to

What is an Array? An Array is a special object in JavaScript used to store multiple values in a single variable. Instead of creating separate variables, let student1 = " John " ; let student2 = " David " ; let student3 = " Alex " ; we can use an array: let students = [ " John " , " David " , " Alex " ]; Each value inside the array is called an element , and every element has an index starting from 0 . Index : 0 1 2 ------------------------- Array : | John | David | Alex | ------------------------- 1. Array length Definition The length property returns the total number of elements present in an array. It is not a function . It is a property of an array object. It is also writable, meaning you can change the length to increase or decrease the array size. Syntax array . length To modify the array length: array . length = newLength ; Parameters None. Returns Returns a number representing the total number of elements in the array. Internal Working Consider this array: let fruits = [ " Apple " , " Orange " , " Mango " ]; Memory representation: Index 0 → Apple 1 → Orange 2 → Mango length = 3 When JavaScript creates the array, it internally stores a special property: { 0 : "Apple" , 1 : "Orange" , 2 : "Mango" , length: 3 } Whenever you access: fruits . length JavaScript simply returns the value stored in the length property. It does not count the elements every time. This makes length very fast. Example 1 let fruits = [ " Apple " , " Orange " , " Banana " ]; console . log ( fruits . length ); Output 3 Example 2 - Updating Length let numbers = [ 10 , 20 , 30 , 40 ]; numbers . length = 2 ; console . log ( numbers ); Output [ 10 , 20 ] JavaScript removes the remaining elements. Example 3 - Increasing Length let colors = [ " Red " , " Blue " ]; colors . length = 5 ; console . log ( colors ); Output [ "Red" , "Blue" , empty × 3 ] The new positions become empty slots . Real-Time Example Imagine an E-commerce Shopping Cart . let cart = [ " Laptop " , " Mouse " , " Keyboard " ]; co

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