简体   繁体   中英

Javascript -> how to recursively add an array of numbers?

I can't seem to figure out what's wrong with this code -> keeps throwing a "Maximum call stack size exceeded" error.

function arrayIntSum(array) {
    if (array === []){
        return 0;
    }
    else return array.shift() + arrayIntSum(array); 
} 

Javascript objects are compared by reference.

[] creates a new array instance, which will will never equal your variable.

You want to check the length .

function arrayIntSum(array) {
    if (array.length === 0){
        return 0;
    }
    else return array.shift() + arrayIntSum(array); 
} 

You should check by this way : a.length==0

you compared a with [] , being a '[]' literal , it has different memory space. and a has different memory space. So they are never equal. so recursion cross its limit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM