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

Can the length of an array be changed in JavaScript?

青灯夜游
青灯夜游Original
2021-11-03 17:14:224856browse

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

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

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);

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!

Statement:
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