将数组元素组合在一起时,Javascript 拼接功能不起作用

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

我正在编写一个计算器应用程序。 html 中的按钮将元素添加到数组中。当用户点击 = 时,它将遍历数组并组合之间没有数学符号的数字。但是,每次组合 2 个数字时,我都必须删除一个元素。

let equation = [1,2,3,"/",1,2,3];
combineNumbers();

function combineNumbers()//call to start finding solution by merging numbers
{
    for(let i = 1; i < equation.length;i++)//iterates length of equation starting at 1
    {
        if(isFinite(equation[i-1]) && isFinite(equation[i]))//checks if equation[i] and the index before it are numbers
        {
            equation[i-1] = '' + equation[i-1] + equation[i];//combines equation[i] and the index before
            equation.splice[i];//removes element at index i
        }
        else
        {
            i++;
        }

    }
    console.log(equation);
}

我尝试向后迭代数组的长度,这进一步破坏了它。 我尝试过不同版本的拼接,包括

equation.splice[i]
equation.splice[i,1]

equation.splice[i] 的当前输出为 [12,23,3,"/",12,23,3]。应该是[123,"/",123]

javascript arrays splice
1个回答
0
投票

您混淆了

[ ]
(索引/属性访问)和
( )
(函数调用)。应该是
equation.splice(i, 1)

© www.soinside.com 2019 - 2024. All rights reserved.