Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript array.length

length属性以32位无符号整数的形式返回数组中的元素数。我们也可以说 length 属性返回一个数字,该数字表示数组元素的数量。返回值始终大于最大数组索引。
length 属性还可以用于设置数组中的元素数。我们必须将赋值运算符与length属性结合使用以设置数组的长度。
JavaScript中的 array.length 属性与 array.size相同()方法中的jQuery。在JavaScript中,使用 array.size()方法无效,因此,我们使用 array.length 属性来计算数组的大小。

语法

以下语法用于返回数组长度
array.length
以下语法用于设置数组的长度
array.length = number
为了更好地理解,让我们看一些使用 array.length 属性的图示。

示例1

一个简单的示例,以了解如何使用 array.length 属性计算数组的长度。
<html>
<head>
<title> array.length </title>
</head>
<body>
<h3> Here, we are finding the length of an array. </h3>
<script>
var arr = new Array( 100, 200, 300, 400, 500, 600 );
document.write(" The elements of array are: " + arr);
document.write(" <br>The length of the array is: " + arr.length);
</script>
</body>
</html>
输出
在输出中,我们可以看到数组的长度为 6 ,该长度大于数组最高的值指数。在上面的示例中,指定数组的最高索引为 5。
JavaScript array.length属性

Example2

在此示例中,我们使用 array.length 属性设置数组的长度。最初,数组包含两个元素,因此开始时的长度为2。然后将数组的长度增加到9。
在输出中,数组的值用逗号分隔。增加长度后,该数组包含两个定义的值和七个未定义的值,以逗号分隔。然后,我们插入五个数组元素并进行打印。现在,该数组包含七个已定义值和两个未定义值。
<html>
<head>
<title> array.length </title>
</head>
<body>
<h3> Here, we are setting the length of an array. </h3>
<script>
var arr = [100, 200];
document.write(" Before setting the length, the array elements are: " + arr);
arr.length = 9;
document.write("<br><br> After setting the length, the array elements are: " + arr);
// It will print [ 1, 2, <7 undefined items> ]
arr[2] = 300;
arr[3] = 400;
arr[4] = 500;
arr[5] = 600;
document.write("<br><br> After inserting some array elements: " + arr);
</script>
</body>
</html>
输出
JavaScript array.length属性
在下一个示例中,我们将使用非数字索引测试数组的length属性。

Example3

在在此示例中,数组的索引为非数字。在此,数组包含五个具有非数字索引的元素。我们在给定数组上应用length属性,以查看效果。现在,让我们看看 array.length 属性如何在数组的非数字索引上工作。
<html>
<head>
<title> array.length </title>
</head>
<body>
<h3> There are five array elements but the index of the array is non numeric. </h3>
<script>
var arr = new Array();
arr['a'] = 100;
arr['b'] = 200;
arr['c'] = 300;
arr['d'] = 400;
arr['e'] = 500;
document.write("The length of array is: " + arr.length);
</script>
</body>
</html>
输出
在输出中,我们可以看到数组的长度显示为 0 。执行完以上代码后,输出-
 JavaScript array.length属性
我们还可以使用length属性来找出字符串中的单词数。让我们用一个示例来理解它。

Example4

在此示例中,我们使用length属性显示字符串中存在的单词数。在这里,我们正在创建一个数组,并对数组元素使用 split()函数。我们正在从空格( "" )字符中拆分字符串。
如果我们直接将length属性应用于字符串,则可以得到字符串中的字符数。但是在此示例中,我们将了解如何计算字符串中的单词数。
<html>
   <head>
      <title> array.length </title>
   </head>
   <body>
      <script>
var str = "Welcome to the lidihuo.com";
var arr = new Array();
arr = str.split(" ");
document.write(" The given string is: " + str);
document.write("<br><br> Number Of Words: "+ arr.length);
document.write("<br><br> Number of characters in the string: " + str.length);
      </script>
   </body>
</html>
输出
JavaScript array.length属性
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4