为什么这些未定义的变量不等于javascript?

时间:2016-07-05 16:07:29

标签: javascript undefined

假设我有以下事件处理程序:

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,不应该是真的吗?如果这是错误的方法,我怎样才能测试变量是否未定义?

1 个答案:

答案 0 :(得分:1)

在以这种方式设置时你必须要小心,通常事情应该是字符串,如果你设置一个不是字符串的值,它将首先被强制转换为字符串,然后分配。

download attribute确实是一个DOMString,这意味着你分配给它的任何东西都会被强制转换成一个字符串,如果它已经没有了,所以当你指定undefined时,它就是&#39 ; s实际上是第一次被强制转移到"undefined"并存储。

当您将其退回并将其与undefined进行比较时,您实际上在做:

console.log("undefined" === undefined)

因此获得false。如果您确实想要将其删除(这是因为想要将其设置为undefined(或null),则可以使用removeAttribute

e.currentTarget.removeAttribute('download')
相关问题