为什么这些未定义的变量不等于javascript?
Why are these undefined variables not equal javascript?
假设我有以下事件处理程序:
function handleCsvDump(e) {
console.log(e.currentTarget.getAttribute('download'));
e.currentTarget.download = undefined;
console.log(e.currentTarget.getAttribute('download'));
console.log(e.currentTarget.getAttribute('download') === undefined);
单击相应按钮时记录到控制台的信息是:
mycsv.csv
undefined
false
为什么最后一个值是false
?既然e.currentTarget.getAttribute('download')
是undefined
,不应该是真的吗?如果这是错误的方法,我该如何测试变量是否未定义?
这样设置的时候一定要小心,通常是字符串,如果你设置的值不是字符串,它会先被强制转换为字符串,然后再赋值。
download
attribute 确实是一个 DOMString,这意味着你分配给它的任何东西都将首先被强制转换为一个字符串,如果它还没有的话,所以当你分配 undefined
时,它实际上是第一个强制为 "undefined"
并存储。
当您将其取回并与 undefined
进行比较时,您实际上在做:
console.log("undefined" === undefined)
因此得到false
。如果你真的想删除它,这意味着要将它设置为 undefined
(或 null
),你可以改为使用 removeAttribute
:
e.currentTarget.removeAttribute('download')
假设我有以下事件处理程序:
function handleCsvDump(e) {
console.log(e.currentTarget.getAttribute('download'));
e.currentTarget.download = undefined;
console.log(e.currentTarget.getAttribute('download'));
console.log(e.currentTarget.getAttribute('download') === undefined);
单击相应按钮时记录到控制台的信息是:
mycsv.csv
undefined
false
为什么最后一个值是false
?既然e.currentTarget.getAttribute('download')
是undefined
,不应该是真的吗?如果这是错误的方法,我该如何测试变量是否未定义?
这样设置的时候一定要小心,通常是字符串,如果你设置的值不是字符串,它会先被强制转换为字符串,然后再赋值。
download
attribute 确实是一个 DOMString,这意味着你分配给它的任何东西都将首先被强制转换为一个字符串,如果它还没有的话,所以当你分配 undefined
时,它实际上是第一个强制为 "undefined"
并存储。
当您将其取回并与 undefined
进行比较时,您实际上在做:
console.log("undefined" === undefined)
因此得到false
。如果你真的想删除它,这意味着要将它设置为 undefined
(或 null
),你可以改为使用 removeAttribute
:
e.currentTarget.removeAttribute('download')