javascript - instanceof contradicts the object type returned by typeof method -
here have array of number containing 6 elements.
var arr=[1.22,2.33,2.002,3.992,3.05,5.44];
then store each element inside variable , tried find out type of object is.i tried both typeof , instanceof .typeof saying variable used contain array value number instance of saying not number.so 1 correct..
then changed array little .used string values instead of number inside array..
var arr=["1.22","2.33","2.002","3.992","3.05","5.44"];
here typeof declaring values number type while instanceof saying opposite. can safe use typeof instead of instanceof .so question when use typeof , when use instanceof , how can avoid type of confusion??
code:
<script> function init() { var arr = ["1.22", "2.33", "2.002", "3.992", "3.05", "5.44"]; (i = 0; < arr.length; i++) { var bag = arr[i]; alert(typeof bag == 'string'); alert(bag instanceof string); } } window.onload = init; </script>
typeof saying variable used contain array value number instance of saying not number.so 1 correct.
both. :-)
javascript has both primitive , object versions of numbers, strings, , booleans. typeof
says "number"
primitive numbers, not objects, , not instanceof number
.
var = 5; console.log(typeof a); // "number" console.log(a instanceof number); // false
it's very rare you'll ever want explicitly create , keep reference object version of number, string, or boolean.
so why have them? can seem have methods on primitives. let's @ a
variable above again, , add statement end:
var = 5; console.log(typeof a); // "number" console.log(a instanceof number); // false console.log(a.tofixed(3); // "5.000"
huh? a
refers primitive number. primitives don't have methods. how call tofixed
method?
the answer javascript engine temporarily promotes primitive equivalent object type, uses object type's methods, , throws away object. (in theory; in practice, of course, engines optimize process.)
you can create number
instance:
var = new number(5); console.log(typeof a); // "object" console.log(a instanceof number); // true
...but again, it's very, rare thing need do.
Comments
Post a Comment