1 <script type="text/javascript"> 2 let array = [5, [[4, 3], 2, 1]]; 3 let result = a(array); 4 function a(value) { 5 let result = 0; 6 for (let index = 0; index < value.length; index++) { 7 if (index == 0 && !(value[index] instanceof Array)) { 8 result += value[index]; 9 } else if (index == 0 && value[index] instanceof Array) { 10 result += a(value[index]); 11 } else if (index > 0 && value[index] instanceof Array) { 12 result -= a(value[index]); 13 } else { 14 result -= value[index]; 15 } 16 } 17 return result; 18 } 19 20 console.log("计算结果:" + result); 21 </script>
PS:多刷算法题,多多益善,注意总结。