我正在尝试在输入值为null但if语句不起作用时捕获该元素。
for (let i = 0; i<esquema.length; i++){
if (esquema[i].checked){
console.log(esquema[i].value);
if (esquema[i].value == null){
console.log ("Actually null");
}
}
}
输出应为
null
Actually null
但是我得到的却不是
null
undefined
有人可以帮我吗?
答案 0 :(得分:0)
如果HTMLElement的value
不是undefined
(<input>
,...)元素,则为<button>
,或者为字符串。由于不是undefined
(因为它记录了null
,并且null == undefined
是正确的),因此必须是"null"
才能记录null
,但不会等于null
。
尽管大多数控制台的打印null
和"null"
的方式有所不同,但同时记录两者并比较结果以查看差异。
答案 1 :(得分:0)
我已经检查了您的功能,如果接收到的值为空,那么它将起作用。它不会检查数据类型,而只是匹配值。
var esquema = [
{
checked: true,
value: "None"
},
{
checked: true,
value: null
}
];
for (let i = 0; i<esquema.length; i++){
if (esquema[i].checked){
console.log(esquema[i].value);
if (esquema[i].value === null){
console.log ("Actually null");
}
}
}
在您的情况下,我假设esquema是一组复选框,并且我确定您将无法将值设置为“ null”。如果未将值添加到节点,则在任何情况下都将是“ undefined”,而不是“ null”。