Friday 14 September 2018

JavaScript: Array slicing

Slicing is used to get sub array from given array.

Example
Description
slice(start,end)
Returns sub array from index start (included) to end index (excluded).
slice(start)
Returns elements from start to till end

array.html
<!DOCTYPE html>

<html>

<head>
    <title>Array</title>
</head>

<body>
    <script type="text/javascript">
        function printArray(arr) {
            document.write("<br />Elements in array are<br />");
            for (i = 0; i < arr.length; i++) {
                document.write(arr[i] + " ");
            }
            document.write("<br />");
        }

        var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        var arr1 = arr.slice(2, 5);
        var arr2 = arr.slice(2, 3);
        var arr3 = arr.slice(2);

        document.write("arr = " + arr + "<br />");
        document.write("arr1 = " + arr1 + "<br />");
        document.write("arr2 = " + arr2 + "<br />");
        document.write("arr3 = " + arr3 + "<br />");
    </script>
</body>

</html>

Open above page in browser, you can able to see following data.

arr = 1,2,3,4,5,6,7,8,9
arr1 = 3,4,5
arr2 = 3
arr3 = 3,4,5,6,7,8,9


Previous                                                 Next                                                 Home

No comments:

Post a Comment