The idea of the code is simple: Check the arguments types, if it is a number, add all the numbers. If the type is a string that has a number, extract the number from the string and add it to the other numbers extracted. If there are no numbers at all and only strings, return the message in the console: "All are strings"
.
let result = 0;
function specialMix(...data) {
for (let i = 0; i < data.length; i ) {
if (typeof data[i] === "number") {
result = data[i];
} else if (typeof data[i] === "string") {
if (typeof parseInt(data[i]) === "number") {
result = parseInt(data[i]);
} else if (typeof parseInt(data[i]) === "NaN") {
continue;
} else if (result === 0) {
console.log("All are strings");
}
}
}
return result;
}
console.log(specialMix(10, 20, 30)); // 60
console.log(specialMix("10Test", "Testing", "20Cool")); // 30
console.log(specialMix("Testing", "10Testing", "40Cool")); // 50
console.log(specialMix("Test", "Cool", "Test")); // All are Strings
The first test (console.log) for the code worked and gave the required result , but the rest of the tests gave NaN
, and I don't understand why that happened. I don't understand what's wrong in the logic of the code.
CodePudding user response:
At first you should put let result = 0
in your function to reset its value whenever you call the function again.
Then if type of the data[i]
was not number, in your else if
you can change your condition to check if parseInt()
of that value is true or not (if not that means that in NAN) so you won't need another condition to check if that's NAN.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
function specialMix(...data) {
let result = 0;
for (let i = 0; i < data.length; i ) {
if (typeof data[i] === "number") {
result = data[i];
} else if (typeof data[i] === "string") {
if (parseInt(data[i])) {
result = parseInt(data[i]);
}
}
}
if (result == 0) return 'All are strings'
return result;
}
console.log(specialMix(10, 20, 30)); // 60
console.log(specialMix("10Test", "Testing", "20Cool")); // 30
console.log(specialMix("Testing", "10Testing", "40Cool")); // 50
console.log(specialMix("Test", "Cool", "Test")); // All are Strings
</script>
</body>
</html>
At the and you can check if result
is still 0 if yes it will return the message, else it will return the value if result
variable.