[英]Delete last letter of a string of numbers
I'm trying to make a calculator. 我正在尝试制作一个计算器。 The code inside the Plus functions work correctly and concatenates the string.
Plus函数中的代码可以正常工作并连接字符串。 Pressing these two buttons below...
按下下面的这两个按钮...
document.getElementById('Textbox').innerHTML += '5';
document.getElementById('Textbox').innerHTML += '9';
Results in the intended 59 being printed to screen. 结果将预期的59打印到屏幕上。
I want to go back to 5, deleting the 9, so the Calculator's CE button. 我想回到5,删除9,所以是计算器的CE按钮。 But this code below makes the number on screen 58. How do I force JS to see this as a string type?
但是下面的代码在屏幕58上显示了数字。如何强制JS将其视为字符串类型?
document.getElementById('Textbox').innerHTML--;
For that use substring method 为此,使用子字符串方法
var a = "59";
a = a.substring(0, a.length - 1);
console.log(a);
result: 5
I would call split on innerHtml to cast it to an array of characters. 我会在innerHtml上调用split将其转换为字符数组。 I would then use the pop method to remove the last character.
然后,我将使用pop方法删除最后一个字符。 And then use join to create a string that you can assign to innerHtml.
然后使用join创建一个可以分配给innerHtml的字符串。
const textBoxElement = document.getElementById('Textbox'); // create an array of characters const innerHtml = textBoxElement.innerHTML.split(''); // remove the last character innerHtml.pop(); // create and assign a string textBoxElement.innerHtml = innerHtml.join('');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.