如以下示例所示:
document.getElementById('test1').value = null;
document.getElementById('test2').value = undefined;
<input id="test1" value="DEFAULT TEXT" />
<input id="test2" value="DEFAULT TEXT" />
输入的值在设置为 null
时会重置,但为什么在设置为 undefined
时也不会重置?
为什么它将值设置为字符串 "undefined"
而不是?
最佳答案
.value
是一个字符串并且需要一个字符串,因此清空它的正确方法是使用空字符串:
/*...*/.value = "";
分配 undefined
将导致它被字符串化,这导致 "undefined"
,而 null
不能被字符串化,因此 spec 表示,将 null
分配给 .value
就像使用空字符串一样。
关于javascript - 为什么将输入值设置为 undefined 不为空呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54371503/