Home > Web Front-end > JS Tutorial > How to use index to access elements in array object in js

How to use index to access elements in array object in js

醉折花枝作酒筹
Release: 2021-08-09 16:30:46
Original
3809 people have browsed it

In the previous article, we learned what an array is and how to create an array. Please see "How to create an array object for js". This time we will learn about the method of using index to access elements in an array object. You can refer to it if necessary.

After we create the array, what do we need to do? Should the elements in the created array be output, and how should they be output? Let’s talk about it today.

Let’s look at a small example first.

<script>
var arr = new Array(3); 
arr[0] = "one";
arr[1] = "two";
arr[2] = "three";
var first = arr[0];
console.log(first);
var last = arr[arr.length - 1];
console.log(last);
</script>
Copy after login

The output result of this small example on the console is

How to use index to access elements in array object in js

You can see that the first element and the last element of this array object are output on the console an element. So how is this done? Let's take a look together.

In this example, you can see that it uses "arr[0]" or "arr[arr.length - 1]", see If we want to access the elements in the array object, we need to use "array object [subscript]" to achieve it.

There is one thing we need to pay attention to: [0] is the first element of the array. [1] is the second element of the array.

If we access an element that does not exist in the array, then we will return "undefined".

For example, if we access not "arr[arr.length - 1]" but "arr[arr.length]", then we "undefined" will be returned. why? We all know that the word length means length. In this example, we are accessing the length of this array. When we access the element of the length of this array, we can know that we are accessing arr[3]. In an array, we use [0] to represent the first element of the array, that means, we will use "length - 1" to represent the last element of the array. In this case, arr[3] will not exist and "undefined" will be returned.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to use index to access elements in array object in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template