简体   繁体   中英

Uncaught TypeError: Reduce of empty array with no initial value

I'm trying to design this very simple application where you input 2 numbers and the app will calculate the smaller common multiple for all numbers between the 2 input numbers.

The function itself works well (judging from the result from console); however when I try to link to HTML with event listeners, glitches happen. Thus I'm assuming I'm making some mistakes when linking to HTML.

With some numbers my app works fine, but with some numbers, for some reason, it doesn't work (for instance, inputs 2 and 10, 7 and 11....etc.). The error says:

Uncaught TypeError: Reduce of empty array with no initial value

Here's my code.

 const smallNum = document.querySelector('#smallernum') const bigNum = document.querySelector('#biggernum') const button = document.querySelector('button') const result = document.querySelector('#result') button.addEventListener('click', () => { result.value = smallestCommons([smallNum.value, bigNum.value]) }) function smallestCommons(arr) { arr.sort((a,b) => ab) let lowerNum = arr[0] let higherNum = arr[1] let newArr = [] let primeOfArr = [] let shortDivisionArr = []; // Create an array of nums inbetween the two extreme nums for(let i = lowerNum; i <= higherNum; i++) { newArr.push(i) } // Create an array of primes up until largest num for(let i = 1; i <= higherNum; i++) { let flag = 0; for(let j = 2; j < i; j++) { if(i % j === 0) { flag = 1; break; } } if(i > 1 && flag === 0) { primeOfArr.push(i) } } // Short Division for(let i = 0; i < primeOfArr.length; i++) { while(newArr.some((num) => num % primeOfArr[i] === 0)) { for(let j = 0; j < newArr.length; j++) { if(newArr[j] % primeOfArr[i] === 0) { newArr[j] = newArr[j] / primeOfArr[i] } } shortDivisionArr.push(primeOfArr[i]) } } return shortDivisionArr.reduce((a,b) => a*b); }
 <div class="container"> <div id="main"> <div class="title"> <h2>This App Helps You Find The Smallest Common Multiple Of Consecutive Numbers Between 2 Nums.</h3> <p>2 nums inclusive. App for demonstration purpose. Please don't use this to cheat on your homework!</p> </div> <div class="calcs"> <div class="inputnums"> <input id="smallernum" type="text" placeholder="Enter a smaller num"> <input id="biggernum" type="text" placeholder="Enter a bigger num"> </div> <button>Click to calculate!</button> <input id="result" type="text" placeholder="Result is here!"> </div> </div> </div>

What am I doing wrong and how can I fix this?

Problem solved. The values passed into the function (smallNum.value and bigNum.value) are strings. Transformed them into integers using parseInt() and it's working now.

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