html - Array index doesn't go out of bound in Javascript -
i creating javascript application want generate arrayindexoutofbound exception. have created array of size 5
, trying insert elements fibonacci series it. ideally, should throw exception after inserting 6th element, not throwing exception. please check code , let me know views. attached code , screenshots of output.
<!doctype html> <html> <head> <title>error handling demo</title> <script type="text/javascript"> var = 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>
what experiencing normal behavior of push
method.
the push() method adds new items end of array, , returns new length.
note: new item(s) added @ end of array.
note: method changes length of array.
please read more here http://www.w3schools.com/jsref/jsref_push.asp
update: if want able constraint max length of array, simplest way constant variable setting holding length of array , checking value array's length. if still wanna throw exception when/if index greater max value, can throwing exception throw 'your exception message'
Comments
Post a Comment