A method of determining the data type of the JavaScript variables-basic knowledge

Source: Internet
Author: User
Tags lowercase

Although JavaScript is a weakly typed language, it also has several data types of its own, namely number, String, Boolean, Object, udefined, and Null. Where object belongs to a complex data type, object is made up of unordered key-value pairs. The remaining few are simple data types. Note: The first letter of the variable type is uppercase, and the variable value is lowercase.
JavaScript does not support custom types, so all values in JavaScript belong to one of these six types.
To figure out what type of data a variable is, use the typeof operator, and note, especially, that TypeOf is an operator, not a method, so the letter ' O ' in typeof is lowercase.
Syntax: typeof temp; Temp is a variable, which can be without parentheses, but it is best to add parentheses for the readability of the program.

JavaScript itself can use it typeof to detect the type of a variable, but some of the results are confusing, for example, the type of the array is "Object".

The following is the result of using TypeOf to determine the various data types

var myfunction = function () {
  console.log (' hello ');

var myObject = {
  foo: ' Bar '
};

var myarray = [' A ', ' B ', ' C '];

var myString = ' Hello ';

var mynumber = 3;

typeof MyFunction;  Return ' function '
typeof MyObject;   Returns ' object '
typeof myarray;   Return to ' object '--Be careful!
typeof MyString;   Returns ' string ';
typeof MyNumber;   Returns ' number '

typeof null;     Return to ' object '--Be careful!


if (myarray.push && myarray.slice && myarray.join) {
  //most likely an array
  //When you see a bird walk like a duck, The bird can be called a duck if it swims like a duck and barks like a duck.
}

if (Object.prototype.toString.call (myarray) = = ' [Object Array] ') {
  //must be an array!
  //This is the surest way to determine whether a variable is an array



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.