当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


JavaScript array.length属性用法及代码示例


length 属性以 32 位无符号整数的形式返回数组中的元素数。我们也可以说 length 属性返回一个表示数组元素数量的数字。返回值总是大于最高数组索引。

length 属性还可用于设置数组中元素的数量。我们必须结合使用赋值运算符和 length 属性来设置数组的长度。

JavaScript 中的 array.length 属性与 jQuery 中的 array.size() 方法相同。在 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 property

例2

在本例中,我们使用 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 property

在下一个示例中,我们将测试具有非数字索引的数组的 length 属性。

例3

在这个例子中,数组的索引是非数字的。这里,数组包含五个具有非数字索引的元素。我们正在给定数组上应用 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 property

我们还可以使用 length 属性来找出字符串中的单词数。让我们通过一个例子来理解它。

例4

在此示例中,我们使用 length 属性来显示字符串中存在的单词数。在这里,我们正在创建一个数组,并为数组元素使用 split() 函数。我们将字符串与空白 (" ") 字符分开。

如果我们直接在字符串上应用 length 属性,那么它会给我们字符串中的字符数。但在这个例子中,我们将了解如何计算字符串中的单词数。

<html>
   <head>
      <title> array.length </title>
   </head>
   
   <body>   
      <script>
var str = "Welcome to the javaTpoint.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 property



相关用法


注:本文由纯净天空筛选整理自 JavaScript array.length property。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。