admin管理员组文章数量:1147241
Why is the value of data-value="2.0"
cast to a String and the value of data-value="2.5"
cast to a Number?
I can handle this fine within my function. I'm just trying to understand a little more about how Javascript handles Numbers and Strings. This kind of caught me off guard.
<a data-value="2.0">2.0</a>
<a data-value="2.5">2.5</a>
$("a").click(function() {
alert(typeof $(this).data( "value"));
});
[ Fiddle With It ]
Why is the value of data-value="2.0"
cast to a String and the value of data-value="2.5"
cast to a Number?
I can handle this fine within my function. I'm just trying to understand a little more about how Javascript handles Numbers and Strings. This kind of caught me off guard.
<a data-value="2.0">2.0</a>
<a data-value="2.5">2.5</a>
$("a").click(function() {
alert(typeof $(this).data( "value"));
});
[ Fiddle With It ]
Share Improve this question edited Oct 26, 2014 at 18:46 Scimonster 33.4k10 gold badges79 silver badges90 bronze badges asked Sep 30, 2014 at 16:48 MattMatt 5494 silver badges11 bronze badges 3 |6 Answers
Reset to default 31Those values are simply strings to vanilla javascript; it's not attempting any conversion on its own.
console.table(
[...document.querySelectorAll("a")]
.map(({dataset:{value}}) => ({
type: typeof value,
value
}))
);
<a data-value="2.0">2.0</a> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script><script>console.config({maximize:true,timeStamps:false})</script><style>.as-console-wrapper{display:block;}</style>
<a data-value="2.5">2.5</a>
jQuery, on the other hand, tries to determine and convert to the appropriate type when accessing data attributes via data()
. It's (arguably) an issue with their implementation. Their documentation (emphasis mine) actually addresses this:
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.
See also HTMLElement.dataset
Looking through jQuery's source code, i have identified the reason.
It will parse it as a number, if, and only if, doing so does not change the string. Source: https://github.com/jquery/jquery/blob/master/src/data.js#L36
(+"2.0") + "" === "2" // !== the original string
(+"2.1") + "" === "2.1" // == the original string
By default anything parsed from an attribute will be a string, you will need to convert it to a number if you need to use it as a number. The best way I've been able to handle this is by wrapping it with the Number function (native javascript)
var number = Number($(this).data("value"));
As tymeJV mentioned, this looks like an issue with how jquery handles autoconversion. If you use "2", it gives a number as well, so I'm guessing its just a weird edge case in how they handle things. I would encourage just using .attr('xxx') and parsing out your data to its known type.
It appears to be treating that ".0" extension of the number like a string.
If all of your data values are going to be coming in in that format, just whip a parseFloat()
on those suckers like this:
$("a").click(function() {
alert(typeof parseFloat($(this).data( "value")));
});
That way it won't matter if they are strings or numbers, they will always be treated like numbers(decimals intact).
I think it's more a question about how jquery identifies numbers. If you use alert(typeof(this.getAttribute("data-value")));
, it spits out that it's a string both times (which is expected). So far as I know, everything in an html attribute is considered a string, just different libraries may have default behavior that interprets them differently.
Also, a shorthand way to get a number would be something along the lines of...
var someNumber = +$(someElt).data("value");
the + will cause type coercion if the returned value is a string, or leave it alone if it's already a number.
本文标签: javascriptHTML5 data* attribute type casting strings and numbersStack Overflow
版权声明:本文标题:javascript - HTML5 data-* attribute type casting strings and numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737239293a1968667.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
0
are always pretended to be strings. Maybe because the last0
is irrelevant and so interpreted as text. For example:2.5
is number and2.50
is string. – TheFrozenOne Commented Sep 30, 2014 at 16:52.data
method will attempt to convert whatever is in thedata-*
attribute - if you want it as the raw string value, use.attr("data-*")
– tymeJV Commented Sep 30, 2014 at 16:53