gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:24:29 27 4
gpt4 key购买 nike

考虑 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com