Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

<script type="text/javascript">   
function saveName (firstName) {
    function capitalizeName () {
        return firstName.toUpperCase();
    }
    var capitalized = capitalizeName();console.log(capitalized instanceof String);
    return capitalized; 
}
console.log(saveName("Robert")); // Returns "ROBERT"
</script>

Question:

I want to check the type of capitalized , so I use capitalized instanceof String? But it shows: false in console, I do not want to try capitalized instanceof Function, Object...It will take too much time, so what is the best way to detect a variable type?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

The best way is to use the typeof keyword.

typeof "hello" // "string"

The typeof operator maps an operand to one of six values: "string", "number", "object", "function", "undefined" and "boolean". The instanceof method tests if the provided function's prototype is in the object's prototype chain.

This Wikibooks article along with this MDN articles does a pretty good job of summing up JavaScript's types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...