Array
JavaScript arrays can grow or shrink in size after creation.
var cities = ["Sochi", "New York"]; alert("cities.length=" + cities.length); var years = new Array(1969, 1970); years[46] = 2015; //You can add array elements in this way. alert("years.length=" + years.length); alert("years=" + years); for (var idx in years) { alert(years[idx]); }
cities.length=2 years.length=47 years=1969,1970,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2015 1969 1970 2015
Methods of Array
splice()
Cut specific elements from an array and create a new array with that elements. You can add other elements when creating a new array using splice().
slice()
It returns a new array of parts of the array.
concat()
Combines two or more arrays to return a copy of the combined array.
reverse()
It flips the order of the array.
The concat() and the slice() methods do not change the original array and return the result as a new array.
The JavaScript engine converts the array into a string separated by a comma (,).
var words = new Array('A','B','C','D','E'); var s1 = words.splice(2,2,'c','d');//Remove two elements from index 2 and add 'c' and 'd' at that position alert(words); alert(s1); var s2 = words.slice(2,4);//Returns a new array from index 2 to index 3 (not including index 4). alert(s2); alert(words);
A,B,c,d,E C,D c,d A,B,c,d,E
for .. in
var lang = ["C", "JAVA", "javascript"]; for (var idx in lang) { alert(lang[idx]); }
C JAVA javascript
Associative arrays
Associative arrays can not access an element using an index. When you create an associative array, you typically use Object. Associative arrays also automatically adjust in size whenever you add a new element or remove an element.
var account = new Object(); account["accountNo"] = "1111-2222-3333"; account["name"] = "John Doe"; account["balance"] = 30000; alert(account["name"]); alert(account.balance);
John Doe 30000
The following shows how to access an element in an associative array.
//Access the getElementsByTagName() element of the associative array document. document.getElementsByTagName('a'); //Access the element ceil() of the associative array Math. Math.ceil(175);
The following statement prints all elements of the document object.
for (var property in document) { alert(property + ":" + document[property]); }
location:http://java-school.net/javascript/Array implementation:[object DOMImplementation] URL:http://java-school.net/javascript/Array documentURI:http://java-school.net/javascript/Array compatMode:CSS1Compat characterSet:UTF-8 charset:UTF-8 inputEncoding:UTF-8 contentType:text/html doctype:[object DocumentType] documentElement:[object HTMLHtmlElement] xmlEncoding:null xmlVersion:null xmlStandalone:false domain:java-school.net referrer: cookie: lastModified:05/23/2025 00:46:20 readyState:interactive title:Array dir: body:[object HTMLBodyElement] head:[object HTMLHeadElement] images:[object HTMLCollection] embeds:[object HTMLCollection] plugins:[object HTMLCollection] links:[object HTMLCollection] forms:[object HTMLCollection] scripts:[object HTMLCollection] currentScript:null defaultView:[object Window] designMode:off onreadystatechange:null anchors:[object HTMLCollection] applets:[object HTMLCollection] fgColor: linkColor: vlinkColor: alinkColor: bgColor: all:[object HTMLAllCollection] scrollingElement:[object HTMLHtmlElement] onpointerlockchange:null onpointerlockerror:null hidden:false visibilityState:visible wasDiscarded:false prerendering:false featurePolicy:[object FeaturePolicy] webkitVisibilityState:visible webkitHidden:false onbeforecopy:null onbeforecut:null onbeforepaste:null onfreeze:null onprerenderingchange:null onresume:null onsearch:null onvisibilitychange:null timeline:[object DocumentTimeline] fullscreenEnabled:true fullscreen:false onfullscreenchange:null onfullscreenerror:null webkitIsFullScreen:false webkitCurrentFullScreenElement:null webkitFullscreenEnabled:true webkitFullscreenElement:null onwebkitfullscreenchange:null onwebkitfullscreenerror:null rootElement:null pictureInPictureEnabled:true onbeforexrselect:null onabort:null onbeforeinput:null onbeforematch:null onbeforetoggle:null onblur:null oncancel:null oncanplay:null oncanplaythrough:null onchange:null onclick:null onclose:null oncontentvisibilityautostatechange:null oncontextlost:null oncontextmenu:null oncontextrestored:null oncuechange:null ondblclick:null ondrag:null ondragend:null ondragenter:null ondragleave:null ondragover:null ondragstart:null ondrop:null ondurationchange:null onemptied:null onended:null onerror:null onfocus:null onformdata:null oninput:null oninvalid:null onkeydown:null onkeypress:null onkeyup:null onload:null onloadeddata:null onloadedmetadata:null onloadstart:null onmousedown:null onmouseenter:null onmouseleave:null onmousemove:null onmouseout:null onmouseover:null onmouseup:null onmousewheel:null onpause:null onplay:null onplaying:null onprogress:null onratechange:null onreset:null onresize:null onscroll:null onsecuritypolicyviolation:null onseeked:null onseeking:null onselect:null onslotchange:null onstalled:null onsubmit:null onsuspend:null ontimeupdate:null ontoggle:null onvolumechange:null onwaiting:null onwebkitanimationend:null onwebkitanimationiteration:null onwebkitanimationstart:null onwebkittransitionend:null onwheel:null onauxclick:null ongotpointercapture:null onlostpointercapture:null onpointerdown:null onpointermove:null onpointerrawupdate:null onpointerup:null onpointercancel:null onpointerover:null onpointerout:null onpointerenter:null onpointerleave:null onselectstart:null onselectionchange:null onanimationend:null onanimationiteration:null onanimationstart:null ontransitionrun:null ontransitionstart:null ontransitionend:null ontransitioncancel:null oncopy:null oncut:null onpaste:null children:[object HTMLCollection] firstElementChild:[object HTMLHtmlElement] lastElementChild:[object HTMLHtmlElement] childElementCount:1 activeElement:[object HTMLBodyElement] styleSheets:[object StyleSheetList] pointerLockElement:null fullscreenElement:null adoptedStyleSheets: pictureInPictureElement:null fonts:[object FontFaceSet] adoptNode:function adoptNode() { [native code] } append:function append() { [native code] } captureEvents:function captureEvents() { [native code] } caretRangeFromPoint:function caretRangeFromPoint() { [native code] } clear:function clear() { [native code] } close:function close() { [native code] } createAttribute:function createAttribute() { [native code] } createAttributeNS:function createAttributeNS() { [native code] } createCDATASection:function createCDATASection() { [native code] } createComment:function createComment() { [native code] } createDocumentFragment:function createDocumentFragment() { [native code] } createElement:function createElement() { [native code] } createElementNS:function createElementNS() { [native code] } createEvent:function createEvent() { [native code] } createExpression:function createExpression() { [native code] } createNSResolver:function createNSResolver() { [native code] } createNodeIterator:function createNodeIterator() { [native code] } createProcessingInstruction:function createProcessingInstruction() { [native code] } createRange:function createRange() { [native code] } createTextNode:function createTextNode() { [native code] } createTreeWalker:function createTreeWalker() { [native code] } elementFromPoint:function elementFromPoint() { [native code] } elementsFromPoint:function elementsFromPoint() { [native code] } evaluate:function evaluate() { [native code] } execCommand:function execCommand() { [native code] } exitFullscreen:function exitFullscreen() { [native code] } exitPictureInPicture:function exitPictureInPicture() { [native code] } exitPointerLock:function exitPointerLock() { [native code] } getAnimations:function getAnimations() { [native code] } getElementById:function getElementById() { [native code] } getElementsByClassName:function getElementsByClassName() { [native code] } getElementsByName:function getElementsByName() { [native code] } getElementsByTagName:function getElementsByTagName() { [native code] } getElementsByTagNameNS:function getElementsByTagNameNS() { [native code] } getSelection:function getSelection() { [native code] } hasFocus:function hasFocus() { [native code] } hasStorageAccess:function hasStorageAccess() { [native code] } hasUnpartitionedCookieAccess:function hasUnpartitionedCookieAccess() { [native code] } importNode:function importNode() { [native code] } open:function open() { [native code] } prepend:function prepend() { [native code] } queryCommandEnabled:function queryCommandEnabled() { [native code] } queryCommandIndeterm:function queryCommandIndeterm() { [native code] } queryCommandState:function queryCommandState() { [native code] } queryCommandSupported:function queryCommandSupported() { [native code] } queryCommandValue:function queryCommandValue() { [native code] } querySelector:function querySelector() { [native code] } querySelectorAll:function querySelectorAll() { [native code] } releaseEvents:function releaseEvents() { [native code] } replaceChildren:function replaceChildren() { [native code] } requestStorageAccess:function requestStorageAccess() { [native code] } requestStorageAccessFor:function requestStorageAccessFor() { [native code] } startViewTransition:function startViewTransition() { [native code] } webkitCancelFullScreen:function webkitCancelFullScreen() { [native code] } webkitExitFullscreen:function webkitExitFullscreen() { [native code] } write:function write() { [native code] } writeln:function writeln() { [native code] } fragmentDirective:[object FragmentDirective] onscrollend:null onscrollsnapchange:null onscrollsnapchanging:null caretPositionFromPoint:function caretPositionFromPoint() { [native code] } nodeType:9 nodeName:#document baseURI:http://java-school.net/javascript/Array isConnected:true ownerDocument:null parentNode:null parentElement:null childNodes:[object NodeList] firstChild:[object DocumentType] lastChild:[object HTMLHtmlElement] previousSibling:null nextSibling:null nodeValue:null textContent:null ELEMENT_NODE:1 ATTRIBUTE_NODE:2 TEXT_NODE:3 CDATA_SECTION_NODE:4 ENTITY_REFERENCE_NODE:5 ENTITY_NODE:6 PROCESSING_INSTRUCTION_NODE:7 COMMENT_NODE:8 DOCUMENT_NODE:9 DOCUMENT_TYPE_NODE:10 DOCUMENT_FRAGMENT_NODE:11 NOTATION_NODE:12 DOCUMENT_POSITION_DISCONNECTED:1 DOCUMENT_POSITION_PRECEDING:2 DOCUMENT_POSITION_FOLLOWING:4 DOCUMENT_POSITION_CONTAINS:8 DOCUMENT_POSITION_CONTAINED_BY:16 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC:32 appendChild:function appendChild() { [native code] } cloneNode:function cloneNode() { [native code] } compareDocumentPosition:function compareDocumentPosition() { [native code] } contains:function contains() { [native code] } getRootNode:function getRootNode() { [native code] } hasChildNodes:function hasChildNodes() { [native code] } insertBefore:function insertBefore() { [native code] } isDefaultNamespace:function isDefaultNamespace() { [native code] } isEqualNode:function isEqualNode() { [native code] } isSameNode:function isSameNode() { [native code] } lookupNamespaceURI:function lookupNamespaceURI() { [native code] } lookupPrefix:function lookupPrefix() { [native code] } normalize:function normalize() { [native code] } removeChild:function removeChild() { [native code] } replaceChild:function replaceChild() { [native code] } addEventListener:function addEventListener() { [native code] } dispatchEvent:function dispatchEvent() { [native code] } removeEventListener:function removeEventListener() { [native code] }
The above example has different results for different browsers. All JavaScript objects are an associative array.
References