我如何计算JS中的字符串变量的值

问题描述 投票:-1回答:1

如果我有一个值为"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 = ''
}
javascript variables calculation
1个回答
0
投票

您可以在分割字符串后使用reduce函数完成此操作

const a = "1+2+3";
const sum = a.split('+').reduce((acc, curr) => Number(acc) + Number(curr));

console.log(sum);
© www.soinside.com 2019 - 2024. All rights reserved.