If JavaScript exceeds the length of the array, no error will be reported

If JavaScript exceeds the length of the array, no error will be reported

Today, I encountered such a problem when I was doing the problem

 while (sum < target) {
	sum += nums[right];

Here, the while loop does not add the limit when the right index exceeds the length of the array, but there is still no error. The program can run normally.

The following reasons are checked here. It is found that when right exceeds the range, the output of num [right] is undefined

console.log(nums[nums.length]) //undefined

When undefined is added to the number, it becomes Nan

console.log(10+nums[nums.length]) // NaN

In the judgment conditions of the while loop, comparing Nan with the number will directly return false, so you can exit the loop without affecting the result.

console.log(NaN>10) //false

Title: 209. Minimum length subarray

When trying to abbreviate it as suffix increment, I forgot to change the initial value of right from – 1 to 0. JavaScript cannot traverse the array through the negative index and will directly return undefined. Therefore, combined with the above example, it will directly exit the first small while loop. Right remains unchanged and will fall into an endless loop.

Error demonstration:

var minSubArrayLen = function(target, nums) {
    let left = 0, right = -1;
    let sum = 0;
    let res = nums.length+1;
    while (right<nums.length) {
        while (sum < target) {
            // right++;
            sum += nums[++right];
        while (sum>=target) {
            res = (res>right-left+1)?right-left+1 : res;
            sum -= nums[left];
            left ++;
    return res>nums.length ?0 : res; 

Read More: