JavaScript Tutorial/Array/Array Length — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 08:25, 26 мая 2010

Append element to the end of an Array by reference the Array.length property

<html>
<head>
<title>Append element to the end of an Array</title>
<script language="javascript" type="text/javascript">
<!--
var x = new Array(2,3,4);
x[x.length] = 1;
alert(x);
//-->
</script>
</head>
<body>
</body>
</html>


Array.length

The length property holds the number of elements in the array.

This property is a read/write variable.

The size of an array can change dynamically at any time.

The length of the array can also be changed by altering the length attribute.

If the length property is overwritten with a number that is larger than the original number, new elements are added to the end of the array and assigned undefined values.

If the length property is overwritten with a number that is smaller than the original number, elements at the end of the array are lost.

If the length of an array is originally 10 and is reduced to 5, the elements in position 6 through 10 are lost.

The following example uses the length Property to Reduce the Number of Elements in an Array.



<html>
    <script language="JavaScript">
    <!--
    coins = new Array("A","B","C","D");
    x = coins.length;  
    coins.length = 3   
    document.write("The coins array contains: ", coins.join(","));
    -->
    </script>
</html>


Get Array length

<html>
<head>
<title>Get Array length</title>
<script language="javascript" type="text/javascript">
<!--
var x = new Array(2,3,4);
alert(x.length);
//-->
</script>
</head>
<body>
</body>
</html>


Get the last element in an Array

<html>
<head>
<title>Get the last element in an Array</title>
<script language="javascript" type="text/javascript">
<!--
var x = new Array(2,3,4);
alert(x[x.length-1]);
//-->
</script>
</head>
<body>
</body>
</html>


Length Automatically Updates

<html>
<head>
<title>Length Automatically Updates</title>
<script language="javascript" type="text/javascript">
<!--
var someArray = new Array();
alert(someArray.length);
someArray[0] = "A";
alert(someArray.length);
someArray[1] = "B";
alert(someArray.length);
//-->
</script>
</head>
<body>
<h1>Length Automatically Updates</h1>
</body>
</html>


Remove elements from array by changing the array length

<html>
<head>
<title>Removing Elements</title>
<script language="javascript" type="text/javascript">
<!--
var x = new Array(0,1,2,3,4);
var firstElement  = x[x.length-1];
x.length = x.length-1;
var secondElement = x[x.length-1];
x.length = x.length-1;
alert(firstElement)
alert(secondElement)
alert(x);
//-->
</script>
</head>
<body>
<h1>Removing Elements</h1>
</body>
</html>