javascript - HTML5 数据属性将 null 和 undefined 转换为字符串

标签 javascript html casting null undefined

考虑 HTML 文件中的示例代码:

 <div id="book"
     data-id="47909"
     data-title="Under The Dome" 
     data-author="Stephen King"
     data-year="2009">
 </div>

选择 book 元素:

book = document.querySelector("#book");

每当我将某些属性设置为 nullundefined 时,它会分别将其设置为字符串“null”、“undefined”:

book.dataset.author = null
typeof book.dataset.author
"string"

book.dataset.year = undefined
typeof book.dataset.year
"string"

同时

let a = null;
typeof a
"object"

let b = undefined;
typeof b
"undefined"

有人可以解释一下为什么它会这样吗?这是否与以下事实有关:由于它是元素属性的性质,最终所有内容都将转换为字符串?

谢谢!

最佳答案

根据 spec of dataset

On getting, the dataset IDL attribute must return a DOMStringMap whose associated element is this element.

并根据 spec of DOMString's value

Attributes have a namespace (null or a non-empty string), namespace prefix (null or a non-empty string), local name (a non-empty string), value (a string), and element (null or an element).

因此该值在返回之前被转换为字符串

String(null); //"null"
String(undefined); //"undefined"
String(1); //"1"

关于javascript - HTML5 数据属性将 null 和 undefined 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48539552/

相关文章:

java - 在java中将前导0字符串转换为整数

javascript - Controller 不是函数得到未定义的错误消息 Angular js

javascript - 缺少要隐藏或显示的 HTML 元素

javascript - Cypress 中失败后重试命令的选项

javascript - 重置 CSS3 动画

C# 泛型和转换问题

javascript - 将下载链接从网络浏览器传递到第三方应用程序

html - 如何用CSS将div放在前台?

javascript - 如何在javascript中增加数据索引

c - 二维数组的指针算术中的类型转换(C)