JavaScript开关语句与大小写不匹配 我有以下问题要解决。
问题5。数字作为字 编写一个脚本,要求输入数字(0-9),并根据输入将数字显示为单词(英语)。 如果输入无效,请打印“非数字”。 使用switch语句。 示例:JavaScript开关语句与大小写不匹配 我有以下问题要解决。,javascript,Javascript,问题5。数字作为字 编写一个脚本,要求输入数字(0-9),并根据输入将数字显示为单词(英语)。 如果输入无效,请打印“非数字”。 使用switch语句。 示例: digit result 2 two 1 one 0 zero 5 five -0.1 not a digit hi not a digit 9 nine 10 not a digit = 这是我的JavaScript和HTML HTML: 问题
digit result
2 two
1 one
0 zero
5 five
-0.1 not a digit
hi not a digit
9 nine
10 not a digit
=
这是我的JavaScript和HTML
HTML:
问题是,当我键入0-9之间的数字时,它会显示默认语句。值是字符串格式的。将其转换为数字,因为
switch
语句不强制类型(与if
语句不同)
或
我还建议使用数组或对象
var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
result.innerHTML = arr[+input.value] || 'Not a Digit';
input.value是否始终是字符串?因此,如果设置为,则我的switch语句将工作,而无需将其解析为数字?@Nasco.Chachev No。从DOM读取的任何内容都是字符串。您必须手动将其转换为数字。您可以使用这很有趣,我认为
开关将强制类型。根据EcmaScript标准:如果输入等于===运算符定义的子句选择器,则…
请参阅
document.addEventListener("DOMContentLoaded",function(){
var input = document.getElementById('textInput');
var button = document.getElementById('react');
var result = document.getElementById('result');
button.addEventListener('click',function(){
switch (input.value) {
case 0:
result.innerHTML = 'zero';
break;
case 1:
result.innerHTML = 'one';
break;
case 2:
result.innerHTML = 'two';
break;
case 3:
result.innerHTML = 'three';
break;
case 4:
result.innerHTML = 'four';
break;
case 5:
result.innerHTML = 'five';
break;
case 6:
result.innerHTML = 'Six';
break;
case 7:
result.innerHTML = 'Seven';
break;
case 8:
result.innerHTML = 'Eight';
break;
case 9:
result.innerHTML = 'Nine';
break;
default:
result.innerHTML = 'not a digit';
break;
}
});
});
switch(+input.value) {
switch(parseInt(input.value, 10)) {
var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
result.innerHTML = arr[+input.value] || 'Not a Digit';