Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

what is the best way to check variable type in javascript

<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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...