Saturday, 1 September 2018

JavaScript: Sparse arrays

In sparse arrays, elements need not have contiguous indexes.

var arr1 = new Array();
arr1[100] = "Hello";
arr1[1234] = 432156;

Eventhough we entered only two elements into the array arr1, the length of the array is 1235 (maximum index + 1 = 1234+1).

sparse.html
<!DOCTYPE html>

<html>

<head>
    <title>sparse arrays</title>
</head>

<body>
    <script type="text/javascript">
        var arr1 = new Array();
        arr1[100] = "Hello";
        arr1[1234] = 432156;

        document.write("arr1 length : " + arr1.length);
    </script>
</body>

</html>

Open above document in browser, you can able to see following text.

arr1 length : 1235

For dense array the length of the array is equal to number of elements in the array, where as for sparse arrays the length of the array can be greater than the number of elements in the array.

Previous                                                 Next                                                 Home

No comments:

Post a Comment