如果我有一个值为"1+2+3"
的变量,如何将其转换为数字? (在这种情况下为6)
这是我的完整代码:
var screen = 0
function buttonActivation(button) {
if (button == '=') {
console.log(screen)
var result = parseFloat(screen)
document.getElementById('screenLine2').innerHTML = result
} else if (screen == 0) {
screen = `${button}`
} else {
screen = `${screen}${button}`
}
document.getElementById('screenLine1').innerHTML = screen
}
function clearScreen() {
screen = 0
document.getElementById('screenLine1').innerHTML = screen
document.getElementById('screenLine2').innerHTML = ''
}
您可以在分割字符串后使用reduce函数完成此操作
const a = "1+2+3";
const sum = a.split('+').reduce((acc, curr) => Number(acc) + Number(curr));
console.log(sum);