JavaScript basic data types and value types and reference types

Source: Internet
Author: User

There are four basic data types in javascript: numeric values (integers and real numbers), string literals (characters or values enclosed in "or"), Boolean (with True or false representations), and null values. The data in the basic type of JavaScript can be either constant or variable. Since JavaScript uses a weakly typed form, a variable or constant of a data does not have to be declared first, but rather the type of its data when it is used or assigned. Of course, you can declare the type of the data first, by automatically stating its data type when the value is assigned.

Variables in JavaScript

The variable in JavaScript is just a placeholder, as the preface has already said, because of the loose type.

Define variables:

var name;

The code above defines a variable named name that can be used to hold any value (such as an uninitialized variable, save a special value--undefined), or initialize the value of a variable.

?
12 varname =”jwy”; //javascript 中的单引号和双引号没有区别,不过要注意正确嵌套name=10;

The first name is initialized to the string value "Jwy", and then changed to a numeric value-100, which is not recommended, but in ECMAScript is effective, and in many cases will do so.

You can also define multiple variables in a single statement, and many JavaScript frameworks do this

?
1 varname=”jwy”,author,age=29;

Each statement plus a semicolon is a good programming habit. However, when you have multiple variables, we recommend wrapping and indenting, which improves readability.

Simple data types

There are 5 simple data types in ECMAScript:Undefined,null,boolea,number and string. There is also a complex data type-Object

typeof operator

Since the variables in JavaScript are loosely typed, it provides a way to detect the data type of the current variable, which is the TypeOf keyword, in the 5 simple data types mentioned in the ECMAScript above, (remember, these 5 are just data types, representing a data type, Just like the int,string type in C #), with the TypeOf keyword, the following values are returned for these 5 data types (shown in string form

"Undefined"----------if the value is undefined undefined

"Boolean"----------if this value is a Boolean value

"String"----------if this value is a string

"Number"----------if this value is a numeric type

"Object"----------if this value is an object or null

"Function"----------if this value is

However, strictly speaking, functions are objects in ECMAScript, each function is an instance of the class of functions, since the function is an object, then it is a reference type, so a function is just a variable name, so it is often seen on many occasions, The function name as a parameter, passed into the function, and then called, which is similar to the delegate in C #, will explain in detail the function of this thing, after all, JavaScript in many things are dependent on the function to implement.

Undefined type

As stated above, 5 types are data types, so the data type is value, undefined value is undefined, note that u is lowercase. If the declared variable is not initialized, the value of the current variable is undefined. However, it is generally recommended to initialize variables as much as possible, but in earlier versions of JavaScript there is no provision for undefined this value, so in some frameworks in order to be compatible with older browsers, the window object will be added undefined value, as follows:

?
123 window[‘undefined‘] = window[‘undefined‘]; //或者window.undefined = window.undefined;

Simply put the undefined property of the Window object to the undefined, in the older browser object does not undefined this property, so if the use of the undefined operation will cause an aberration, so in this way, But at first it would be a bit hard to understand that in older browsers it would be compatible with the old browser because it would return a undefined value because it did not window.undefined the object.

However, variables that contain undefined values are not the same as undefined variables, such as:

?
123 varname;alert(name);//undefinedalert(age);// 错误:age is not defined

A variable that has not been declared can only perform one operation, and none of the others can do it by using the TypeOf operator to detect its data type.

If the execution of a variable that is declared uninitialized and not declared is typeof, it returns the value of undefined. Neither one of them can do real work.

Null type

The value of the null type is NULL, which represents an empty object pointer, does not point to any object, and if the value of a variable is null, the current variable is likely to be a garbage collected object, which is returned "object" when using typeof to monitor null values.

?
12 varperson = null;alert(typeofperson);//”object”

Recommendation: If the variable is the amount to be used to hold the object, it is initialized to NULL, so that it can be detected that the variable has already saved a reference to an object.

Note: The undefined values are derived from null, so performing an equality test on them returns true, such as:

?
1 alert(null== undefind);//true

However, their use is completely different, no matter under what circumstances it is not necessary to set the value of a variable display to undefined, but this rule does not apply to NULL.

Boolean type

This type has only two values: True and False. Although there are only two values, all types of values in JavaScript have values that are equivalent to these two values. To convert a value to the corresponding Boolean value, you can call the Transform function Boolean () (In fact, the Boolean, Object,string,number,function, and so on are all functions, constructors, and can also be understood as a class, Calling the ToString () method with a type will return something like this:

"Function function () {[native code]}", function will be changed accordingly to the respective calling function)

In fact, in the IF statement judgment, the conditions inside will automatically execute a boolean change.

Number Type

There are many values for numeric types, and the most basic of course is decimal, such as:

var num=510;

In addition to decimal, integers can also be octal or hexadecimal, where the first digit of the octal literal must be 0, then the octal number sequence, and if the value in the literal value is out of range, then the leading 0 is ignored. The value of the trailing amount is parsed as a decimal number.

var num1=070;//eight-binary 56
var num2 =079;//invalid octal-resolves to 79
var num3 =08;//invalid octal-resolves to 8

The hexadecimal prefix must be 0x, followed by a hexadecimal number (0~F), regardless of case. Such as:

?
12 var num1 = 0xA;var num2 = 0x1f;

Although it can be represented as octal and hexadecimal, it is converted to a decimal value when computed.

In addition to integers, there are floating-point numbers, and of course, there are no keywords like float in other strongly typed languages.

?
123 varnum1 = 1.1;var num2 =0.1;varnum3 = .1;//有效,但不推荐

When you save an integer, the memory allocation size is only 1/2 of the floating-point number, so when a floating-point number can be converted to an integer, JavaScript is automatically converted to an integer.

Of course, in addition to these values are relatively small, there are some large or small values, can be expressed in scientific notation,

var Num=123.456e10;

The highest precision of a floating-point value is 17 decimal places, but its accuracy is far less accurate than an integer. For example, 0.1+0.2 is not equal to 0.3, but 0.3000000000000004, so when making a judgment, do not use the floating-point addition to judge a value equal to the expected.

In JavaScript, the smallest value is number.min_value, which can be imagined as number is a class, and Min_value is a static variable, storing the minimum value, again, the largest is Number.MAX_VALUE.

If the calculation exceeds this maximum and minimum range, it will be automatically converted to Infinity value, if it is negative, is-infinity, integer is the meaning of infinity,infinity is infinite, that is, positive or negative infinity, with the concept of mathematics is the same. But Infinity is unable to participate in the calculation. You can use the native function to determine whether there is a poor: isfinite (); only in the numeric range will it return true.

In JavaScript, in addition to those ordinary integers, floating-point numbers, maximums, minimums, infinity, there is a special value, which is Nan. This value is used to represent a case where the operand that would have returned a numeric value did not return a numeric value. For example, any number divided by 0 in C # will be an error, throw an exception, but in JavaScript, any number divided by 0 will return Nan, so it does not affect the execution of the code.

Features of Nan:

1. Any operation that designs Nan (for example: nan/0) will return Nan.

2. Nan is not equal to any value, including Nan itself. Such as:

?
1 alert(NaN == NaN);//false

So there's a isNaN () function in JavaScript that takes a parameter, any type, that will help us determine if the parameter is "not a value". It will first try to first say this value to a number. If the value cannot be converted to a number, it returns true after the function is called, which is NaN non-numeric.

As for numeric conversions, this content is extended in JavaScript and is an article that has time to collate.

String type

Strings can be represented by single or double quotation marks, which are equivalent in JavaScript, such as:

?
12 varname = ‘jwy‘;varauthor = “jwy”;

However, it is important to pay attention to nesting correctly.

Strings can be directly assigned by literal values. The length of any string can be obtained by accessing the gas length property.

The strings in JavaScript are immutable, in fact this is the same as in C #, (which is also to improve performance), once the string is created, their values cannot be changed, to change the string saved by a variable, first to destroy the original string, The variable is then populated with another string that contains stationery.

?
12 varname=”jwy”;name = “jwy”+” study javascript”;

Here the first name is to save the string "Jwy", the second line of code will be "Jwy" + "study JavaScript"; The value is re-assigned to name, which first bases a new string that can hold the length, and then populates and destroys the original string.

Almost every value has its own ToString () method, which in the following article will explain where this method came from, it returns the string representation of the corresponding value.

?
12 varage=11;varageToString =age.toString();//”11”

Values, Booleans, objects, and string values all have ToString (), but the null and undefined values do not have this method.

In general, calling the ToString () method does not have to pass arguments, but when you call the ToString method of a number, you can pass a parameter that specifies the cardinality of the numeric value to output (see if you want to output a decimal, binary, octal, hexadecimal representation)

Since null and undefined do not have the ToString method, the call will be an error if it is not known whether it is both, so there is also a way to choose, that is, using the transformation function string (), it can receive any type of value into a string, the processing rule is as follows:

1, if this value has tostring then call directly, and return the result

2, if NULL, returns "NULL"

3, if it is unde, then return "undefined"

Object type

The object type is the originator of the JavaScript reference type, which is the same as in C # and Java, where you can add properties and methods after you create an instance of type object.

?
12 varo = new Object;//有效,不推荐var o =newObject();

In JavaScript, any properties and methods that the object type has also exist in more specific objects.

Each instance has the following properties and methods, as follows:

1, constructor, holds the function used to create the current object. The above constructor is object ();

2, hasOwnProperty, to check whether a given property is in the current object instance, is true, not in the instance, but in the prototype, it is false;

3, isprototypeof, to check if the incoming object is a prototype of another object

4, propertyisenumerable, to check whether a given property can be enumerated using the for...in statement,

5, toString, the string representation of the returned object

6, ValueOf, returns the string, numeric, or Boolean representation of the object, usually the same as the ToString method return value

These are the properties and methods that object has, and all objects inherit these properties and methods because of the inheritance relationship.

Conclusion

Undefined, Null, Boolean, number, string are the basic data types in JavaScript, and object is a reference type. Detecting other types with typeof returns the corresponding string, but when null or an object is detected, it returns "Object", which, if mastered, will not be able to see the point. Incidentally, I would say:

The three Boolean, number, and String are the basic wrapper types in JavaScript, that is, these three are actually constructors, they are instances of functions, they are reference types, As for the string here is the same name as the article string, because in fact, the string refers to a string, here string refers to the constructor of string, which is written in order to better understand, because JavaScript is loosely typed. We can look at examples of string instantiation:

?
1234 varname = String("jwy");alert(typeof name);//"object"var author = "Tom";alert(typeofname);//"string"

As for author, this will have length,substring and so on. These methods, in fact, are the aspects of string here, string is just an instance of string, similar to the string in C #, and string, but here is a special point.

Note that the typeof variable if the value is "string", that is, the variable is a string, in JavaScript, the string is the base type, and in C # or Java, the string is a reference type, but the string in JavaScript is a reference type, Because it is a basic wrapper type defined in JavaScript, in C #, string is actually the same as string. This thing is a bit around, if it is wrong, please point out, to communicate with each other.

Value types and reference types in JavaScript

First, Embrace JavaScript

The ever-classical works JavaScript has multiplied with the popularity of Ajax, and now JavaScript is no longer just a dispensable aid in web development, even with the job of "JavaScript engineer", which belongs to it. I'm afraid you're just a web developer, you have to understand JavaScript, at least you can see the word "familiarity with JavaScript first" in some of the relevant job requirements. Even I'll tell you that you'll be able to develop desktop software with JavaScript, thanks to another development model of Adobe AIR, which uses html+css+javascript to develop air.

Second, value type and reference type topic

As part of the involvement of large object-oriented language-based friends, they try to use JavaScript to simulate the various features of a polygon object, although some simulations seem far-fetched, but also give us insight into the power and flexibility of JavaScript. This article does not discuss JavaScript object-oriented programming technology. Let's talk about two types of variables in javascript: value types and reference types, which often make you think of "stacks", plus "reference addresses" or "pointers" related concepts, and people with Java or C # programming experience believe they are not unfamiliar to either type. Here is an example of how these two types are embodied, used, and noted in JavaScript.

Iii. what are JavaScript value types and reference types

(1) value type: Numeric, Boolean, null, undefined.

(2) Reference type: object, array, function.

Iv. How to understand value types and reference types and examples

We can use "chain store" and "chain key" to understand, do not know the following analogy does not fit, ^-^.

(1) Value type Understanding: The exchange of variables is equal to a new place in accordance with the chain of standards (unified store understanding of the same variable content) opened a new branch, so that the new shop and other old shops are not related to each other and operate.

Value type Example

?
123456789 function chainstore () {    var store1= ' Nike China '    var store2=store1;    store1= ' Nike U.S.A. '    alert (store2); //nike China } chainstore (); //a value type (which can also be called the basic type) Store2 passed to another variable (assignment), is actually allocated a new memory space, so change the value of Store1 has no effect on Store2, Because it is not like a reference type, the exchange of a variable is actually an address that refers to the same content.

(2) Reference type Understanding: The exchange of variables is equal to the existing store key (variable reference address) copy one to the other boss, at this time two bosses at the same time to manage a shop, the behavior of two bosses can have a shop in the operation of the impact.

Reference type examples

?

12345678910 function chainstore () {    var store1=[ ' Nike China ' ];    var store2=store1;    alert (store2[0]); //nike China    store1[0]= ' Nike U.S.A. '    alert (store2[0]); //nike U.S.A. } chainstore ();

JavaScript basic data types and value types and reference types

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.