Home  >  Article  >  Web Front-end  >  How to determine the data type of JavaScript variables

How to determine the data type of JavaScript variables

巴扎黑
巴扎黑Original
2017-08-21 10:43:231121browse

Although Javascript is a weakly typed language, it also has several data types of its own, namely: Number, String, Boolean, Object, Udefined, and Null. Among them, Object is a complex data type, and Object consists of unordered key-value pairs. The remaining several types are simple data types. Note: The first letter of the variable type is capitalized, while the first letter of the variable value is lowercase. JavaScript does not support custom types, so all values ​​in JavaScript belong to one of these six types. To find out what data type a variable is, you need to use the typeof operator. Note that typeof is an operator, not a method. Therefore, the letter "o" in typeof is lowercase. Syntax: typeof temp; //temp is a variable. You don’t need to add parentheses here, but for the readability of the program, it is best to add parentheses.

JavaScript itself can use typeof to detect the type of variables, but some results are confusing. For example, the type of the array is actually "Object".

The following are the judgment results of various data types using typeof

var myFunction = function() {
  console.log("hello");
};
var myObject = {
  foo : "bar"
};
var myArray = [ "a", "b", "c" ];
var myString = "hello";
var myNumber = 3;
typeof myFunction;  // 返回 "function"
typeof myObject;   // 返回 "object"
typeof myArray;   // 返回 "object" -- 小心哦!
typeof myString;   // 返回 "string";
typeof myNumber;   // 返回 "number"
typeof null;     // 返回 "object" -- 小心哦!
if (myArray.push && myArray.slice && myArray.join) {
  // 很可能是一个数组
  // 当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子。
}
if (Object.prototype.toString.call(myArray) === "[object Array]") {
  // 肯定是一个数组!
  // 这是判断一个变量是否为数组的最可靠方法
}

The above is the detailed content of How to determine the data type of JavaScript variables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn