Get the App
SLTechnology News&Howtos  ›  Development  › 

The method of element Operation in JavaScript Array

Shulou Source: shulou.com Published: 2022-06-01 05:38:51 10月03日 Update

This article mainly introduces the JavaScript array element operation method related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this JavaScript array element operation method article will have a harvest, let's take a look at it.

Access the first array element

Example

Fruits = ["Banana", "Orange", "Apple", "Mango"]

Var first = fruits [0]

Access the last array element

Example

Fruits = ["Banana", "Orange", "Apple", "Mango"]

Var last = fruits [fruits.length-1]

Traversing array elements

The safest way to traverse an array is to use the "for" loop:

Example

Var fruits, text, fLen, i

Fruits = ["Banana", "Orange", "Apple", "Mango"]

FLen = fruits.length

Text = ""

For (I = 0; I < fLen; iTunes +) {

Text + = "" + fruits [I] + ""

}

You can also use the Array.foreach () function:

Example

Var fruits, text

Fruits = ["Banana", "Orange", "Apple", "Mango"]

Text = ""

Fruits.forEach (myFunction)

Text + = ""

Function myFunction (value) {

Text + = "" + value + ""

}

Add array elements

The best way to add new elements to an array is to use the push () method:

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Fruits.push ("Lemon"); / / add a new element (Lemon) to fruits

You can also use the length attribute to add new elements to the array:

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Fruits [fruits.length] = "Lemon"; / / add a new element (Lemon) to fruits

Warning!

Add elements with the highest index to create undefined "holes" in the array:

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Fruits [6] = "Lemon"; / / add a new element (Lemon) to fruits

This is the end of the article on "methods for manipulating JavaScript array elements". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to operate JavaScript array elements". If you want to learn more, you are welcome to follow the industry information channel.

Tags: Element array method instance knowledge content article highest security value function available in attribute easy to operate article easy to understand more see index industry Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info vpn Huawei Redmi Shulou Information