我正在编写一个计算器应用程序。 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]
您混淆了
[ ]
(索引/属性访问)和( )
(函数调用)。应该是equation.splice(i, 1)
。