最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Array index doesn't go out of bound in Javascript - Stack Overflow

programmeradmin0浏览0评论

I am creating a JavaScript application where I want to generate an ArrayIndexOutOfBound Exception. I have created an array of size 5 and I am trying to insert elements from the Fibonacci series into it. Ideally, it should throw an exception after inserting 6th element, but it is not throwing any exception. Please check the code and let me know your views. Attached code and screenshots of the output.

<!DOCTYPE html>
<html>

<head>
    <title>Error Handling Demo</title>
    <script type="text/javascript">

    var i = 1;
    var fibona = [];
    fibona.length=5;

        function generateNext()
        {   
            if(i>1)
                {
                    number1.value = number2.value;
                    number2.value = number3.value;
                }

            number3.value = parseInt(number1.value) + parseInt(number2.value);
            i++;

            fibona.push({'num1':number1.value, 'num2':number2.value, 'num3':number3.value});
        }

    </script>
</head>

<body>
    <h1>Fibonacci Series Game</h1>

    <p>
        Number 1 :
        <input type = "number" name = "number1" value = 0 id = "num1">
    </p>

    <p>
        Number 2 :
        <input type = "number" name = "number2" value = 1 id = "num2">
    </p>

    <p>
        Next Number :
        <input type = "number" name = "number3" id = "num3">
    </p>

    <p>
        <input type = "button" name = "generatenext" value = "Generate Next Number" onclick = "generateNext()">
    </p>

</body>

</html>

I am creating a JavaScript application where I want to generate an ArrayIndexOutOfBound Exception. I have created an array of size 5 and I am trying to insert elements from the Fibonacci series into it. Ideally, it should throw an exception after inserting 6th element, but it is not throwing any exception. Please check the code and let me know your views. Attached code and screenshots of the output.

<!DOCTYPE html>
<html>

<head>
    <title>Error Handling Demo</title>
    <script type="text/javascript">

    var i = 1;
    var fibona = [];
    fibona.length=5;

        function generateNext()
        {   
            if(i>1)
                {
                    number1.value = number2.value;
                    number2.value = number3.value;
                }

            number3.value = parseInt(number1.value) + parseInt(number2.value);
            i++;

            fibona.push({'num1':number1.value, 'num2':number2.value, 'num3':number3.value});
        }

    </script>
</head>

<body>
    <h1>Fibonacci Series Game</h1>

    <p>
        Number 1 :
        <input type = "number" name = "number1" value = 0 id = "num1">
    </p>

    <p>
        Number 2 :
        <input type = "number" name = "number2" value = 1 id = "num2">
    </p>

    <p>
        Next Number :
        <input type = "number" name = "number3" id = "num3">
    </p>

    <p>
        <input type = "button" name = "generatenext" value = "Generate Next Number" onclick = "generateNext()">
    </p>

</body>

</html>

Share Improve this question edited Aug 29, 2016 at 6:42 Kristijan Iliev 4,99710 gold badges30 silver badges51 bronze badges asked Aug 29, 2016 at 6:35 pavan shahpavan shah 1292 silver badges13 bronze badges 2
  • In JS, setting an array's .length property does not set the maximum number of elements that the array can contain. I'm not aware of any way to restrict the number of elements. – nnnnnn Commented Aug 29, 2016 at 6:39
  • @TravisRodman - No, that will just return undefined (if reading the value) or happily create the element at that index (if writing the value). – nnnnnn Commented Aug 29, 2016 at 6:41
Add a ment  | 

3 Answers 3

Reset to default 2

What you are experiencing is the normal behavior of the push method.

The push() method adds new items to the end of an array, and returns the new length.

Note: The new item(s) will be added at the end of the array.

Note: This method changes the length of the array.

Please read more here http://www.w3schools./jsref/jsref_push.asp

UPDATE: If you want to be able to constraint the max length of the array, the simplest way would be with a constant variable setting holding the length of the array and checking this value with the array's length. If you still wanna throw an exception when/if the index is greater than this max value, then you can do it by throwing your exception like this throw 'your exception message'

Javascript Array push would increase the length anyway.

Eg. if you declare var arr = []; and arr.length = 2 then push something arr.push("4") would give the final length as 3 which adds to your initial length. The only way to check if the array exceeds length is by traversing the array and paring if index is greater than length of the array. The other way is to prevent the push by validating through a variable with predefined length.

You can prevent the push by paring it with the predefined length and in else raise your custom error like this

throw new Error("outOfBoundException")

Learn more about custom exception in javascript here Custom Exceptions in JavaScript

  1. Regarding your ment: You can just store the length in some variable, e.g.

    var data = [];
    var length = 5; // user defined length
    
    for(var i = 0; i < length; i++) {
        data.push(createSomeObject());
    }
    

In your case your doing the same as above but your not looping through the length.

  1. You might also think of using new Array() like below

new Array(4); creates an empty array of length 4. But

new Array('4'); creates an array containing the value '4'.

But not suggested as jsLint does not like new Array() because the constructer is ambiguous.

发布评论

评论列表(0)

  1. 暂无评论