繁体   English   中英

为什么这些未定义的变量不等于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属性确实是DOMString,这意味着分配给它的任何内容(如果尚未undefined话)将首先被强制转换为字符串,因此当您分配undefined ,它实际上首先被强制转换为"undefined"并被存储。

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

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

因此越来越false 如果确实要删除它(这是通过将其设置为undefined (或null )来暗示的),则可以改用removeAttribute

e.currentTarget.removeAttribute('download')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM