Home > Web Front-end > Front-end Q&A > Can the length of an array be changed in JavaScript?

Can the length of an array be changed in JavaScript?

青灯夜游
Release: 2021-11-03 17:14:22
Original
5152 people have browsed it

The length of the array can be changed in JavaScript. Methods: 1. Change the length of the array by changing the value of the length attribute of the array. The syntax is "arr.length=length value"; 2. Use unshift(), shift( ), splice() and other methods add or delete array elements to change the array length.

Can the length of an array be changed in JavaScript?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

The length of arrays in JavaScript can be changed.

The length property of JavaScript arrays is variable. We can change the length of the array by changing the value of the length property.

var arr=[55,32,5,90,60,98,76,54];//包含8个数值的数组arr 
document.write(arr.length); //显示数组长度8
arr.length=10; //增大数组的长度
document.write(arr.length); //数组长度已经变为10
Copy after login

And, as the elements of the array increase or decrease, the length will also change. Example:

var arr=[98,76,54,56,76]; // 包含5个数值的数组
document.write(arr.length); //显示数组的长度5
arr[15]=34;  //增加元素,使用索引为15,赋值为34
alert(arr.length); //显示数组的长度16
Copy after login

We can use push(), pop(), unshift(), shift(), splice() and other methods to add or delete array elements to change the array length. Example:

var arr = [0];  //定义数组
console.log(arr.length);  

arr.unshift(1,2);  //一次性增加两个元素
console.log(arr.length);  

arr.shift(0);  //删除1个元素
console.log(arr.length);
Copy after login

Output result:

Can the length of an array be changed in JavaScript?

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of Can the length of an array be changed in JavaScript?. 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