Data Types in Javascript _ basic knowledge-js tutorial

Source: Internet
Author: User
JavaScript is a weak type or dynamic language. This means that you do not need to declare the variable type in advance. During the program running, the type will be automatically determined. This also means that you can use the same variable to save different types of data. Although Javascript is a weak type language, it also has several data types, including Number, String, Boolean, Object, Udefined, and Null. Objects are complex data types, and they are composed of unordered key-value pairs. The other types are simple data types. Note: The first letter of the variable type is in upper case, while the first letter of the variable value is in lower case.

JavaScript does not support custom types, so all values in JavaScript belong to one of these six types.
According to ECMAScript 5.1, javascript contains six data types: Undefined, Null, Boolean, Number, String, and Object. The first five are basic types, and the last one is Object type.

The latest ECMAScript 6 adds another type: Symbol (New Definition of ECMAScript 6)

Basic Data Type

Undefined: there is only one value, which is undefined, meaning "null (no value)", applicable to all data types.
Null: there is only one value. If it is null, it means "Null object (no object)" and only applies to object types. (Literal)
Boolean: has two values: true and false.
Number: the value is a set of 64-bit floating-point numbers that follow the IEEE 754 standard and does not have an integer data structure. There are also three special values: NaN, Infinity, and-Infinity.
String: a set of Unicode characters. Must be included in 'or.

I. String

The string type of JavaScript is used to represent text data. It is a group of 16-bit unsigned integer "elements ". Each element in the string occupies the position of the string. The index of the first element is 0, and index 1 is next. The length of a string is the number of its elements.

Different from the C language, strings in JavaScript are immutable (for example, the string operation in JavaScript must return a new string, and the original string is not changed)

Everything in Javascript is object-based.

Create a string. There are two types.

1. A string created using the literal method, which is a string of the basic type // string

2. Use the String () to create a string of the basic type.

3. Create a String using the constructor new string (), which is an object type // String

Var str1 = "javascript"; // string
Var str2 = String ("javascript"); // string is not recommended
Var str3 = new String ('javascript '); // object

Object and string are also different.

S1 = "2 + 2"; // creates a string primitive
S2 = new String ("2 + 2"); // creates a String object
Console. log (eval (s1); // returns the number 4
Console. log (eval (s2); // returns the string "2 + 2"
Conversion of string objects valueof-string

Console. log (eval (s2.valueOf (); // returns the number 4

Ii. boolean

Do not confuse Boolean objects whose original values are true, false, and false.

1. If a Boolean constructor parameter is not a Boolean value, the parameter is converted to a Boolean value.

2. If the parameter is 0,-0, null, false, NaN, undefined, or an empty string (""), the value of the generated Boolean object is false. any other value, including any object or string "false", will create a Boolean object with a value of true

var x = new Boolean(false);if(x){ console.log(x.valueOf(),typeof x); // false object}

The above code will be executed, which is amazing.

Do not convert a non-Boolean value to a Boolean value by creating a Boolean object. It is correct to directly use the Boolean function.

Var x = Boolean (expression); // var x = new Boolean (expression! During initialization, // falsevar bNoParam = new Boolean (); var bZero = new Boolean (0); var bNull = new Boolean (null ); var bEmptyString = new Boolean (""); var bfalse = new Boolean (false); // truevar btrue = new Boolean (true ); var btrueString = new Boolean ("true"); var bfalseString = new Boolean ("false"); var bSuLin = new Boolean ("Su Lin ");

Iii. Number

According to the ECMAScript standard, JavaScript has only one numeric type: IEEE 754-based dual-precision 64-bit binary format values (-(253-1) to 253-1 ). It does not provide a specific type for integers. In addition to representing floating point numbers, there are also some signed values: + Infinity,-Infinity, and NaN (non-numeric, Not-a-Number)

The numeric type has only one integer. It can be expressed as-0 or + 0 ("0" is a abbreviation of + 0 ). In practice, this has almost no impact. For example, + 0 =-0 is true. However, you may need to note that when dividing by 0:

42/+ 0; // Infinity
42/-0; //-Infinity

If the parameter cannot be converted to a number, NaN is returned.

In non-constructor context (for example, no new operator), Number can be used to perform type conversion.

IsNAN type determination

Number.isNaN(NaN);  // trueNumber.isNaN(Number.NaN); // trueNumber.isNaN(0 / 0)  // true// e.g. these would have been true with global isNaN()Number.isNaN("NaN");  // falseNumber.isNaN(undefined); // falseNumber.isNaN({});   // falseNumber.isNaN("blabla"); // false// These all return falseNumber.isNaN(true);Number.isNaN(null);Number.isNaN(37);Number.isNaN("37");Number.isNaN("37.37");Number.isNaN("");Number.isNaN(" ");

Relation of prototype chain inheritance

Console. log (Number. prototype. _ proto _ = Object. prototype); // true
Console. log (Number. prototype. _ proto _. _ proto _ = Object. prototype. _ proto _); // true
Console. log (Object. prototype. _ proto _ = null); // true
Console. log (typeof Number); // function

Use Number to convert a Date object

Var d = new Date ("December 17,199 5 03:24:00 ");
Console. log (Number (d ));

Iv. Null

Null is a JavaScript literal that represents a null value (null or an "empty" value), that is, no object value is present ). It is one of the original JavaScript values.

Null is a literal (not an attribute of a global object, undefined is)

Console. log (null); // null
Console. log (undefined); // undefined
Console. log (window. null); // undefined
Console. log (window. undefined); // undefined

Difference between null and undefined

console.log(foot);//Uncaught ReferenceError: foot is not definedvar foo;console.log(foo);//undefinedvar bar =null;console.log(bar);//nulltypeof null  // object (bug in ECMAScript, should be null)typeof undefined // undefinednull === undefined // falsenull == undefined // true

Therefore, null can be used to determine the type + value.

5. Undefined

In JavaScript, the term undefined has multiple meanings. the initial Undefined indicates a data type, while the lower-case undefined indicates a unique value of this data type. however, both types of undefined can only exist in documents or standards, and cannot exist in JavaScript code. in JavaScript code, undefined is most likely an attribute of a global object. The initial value of this attribute is the original undefined value mentioned above. In other cases, this undefined is a local variable. Just like other common variables, it has no special characteristics. Its value is not necessarily undefined, but usually it is. the undefined mentioned below refers to window. undefined.

In ES3 (before Firefox4), window. undefined is a common attribute. You can change its value to any true value, but in ES5 (after Firefox4), window. undefined is a data attribute that cannot be written or configured. Its value is always undefined.

The value of an uninitialized variable is undefined, and the value of an undefined parameter that does not pass in real parameters is undefined. If a function returns nothing, undefined is returned by default.

You can use the strictly equal operator to determine whether a value is undefined:

var foo;console.log(foo === undefined);//trueconsole.log(typeof foo === 'undefined');//trueconsole.log(window.foo === undefined);//trueconsole.log(bar === undefined);//Uncaught ReferenceError: bar is not definedconsole.log(typeof bar === 'undefined');//trueconsole.log(window.bar === undefined);//trueconsole.log(typeof undefined == 'undefined'); //trueconsole.log(typeof null == 'object');//trueconsole.log(null == undefined);//trueconsole.log(null === undefined);//false

Summary

The Null value is null, which indicates a Null Object Pointer and does not point to any object.
The Undefined value is undefined, indicating that the attributes of the declarative variable or object are not initialized.
The undefined value is derived from null. Therefore, true is returned when the equality test is performed on them.
Values, Boolean values, objects, and string values all have the toString () method. But null and undefined values do not have this method.
In most cases, parameters are not required to call the toString () method. However, when calling the toString () method of a value, you can pass a parameter: The base number of the output value.

Var num = 10;
Alert (num. toString (); // "10"
Alert (num. toString (2); // "1010"
Alert (num. toString (8); // "12"
Alert (num. toString (10); // "10"
Alert (num. toString (16); // ""

If you do not know whether the value to be converted is null or undefined, you can also use the transformation function String (), which can convert any type of value to a String. The String () function follows the following conversion rules:

● If the value has a toString () method, call this method (without parameters) and return the corresponding result.

● If the value is null, "null" is returned"

● If the value is undefined, "undefined" is returned"

Vi. Object

Everything in Javascript is an Object.

// Objectstypeof {a: 1 }== 'object'; // use Array. isArray or Object. prototype. toString. the call method can be divided from basic objects into array types: typeof [1, 2, 4] === 'object'; typeof new Date () === 'object '; // The following is confusing. Do not use it like this! Typeof new Boolean (true) === 'object'; typeof new Number (1) === 'object'; typeof new String ("abc ") === 'object'; // function typeof function () {}== 'function'; typeof Math. sin = 'function ';

Instantiate an empty Object

Var o = new Object ();
Var o = new Object (undefined );
Var o = new Object (null );
Var o = {};

Prototype

When the attribute is defined as _ proto __: value or "_ proto _": value, the _ proto _ attribute is not created. If the given value is an object or null, the [[Prototype] of the object will be set to the given value. (If the given value is neither an object nor null, the object's prototype will not change .)

var obj1 = {};assert(Object.getPrototypeOf(obj1) === Object.prototype);var obj2 = { __proto__: null };assert(Object.getPrototypeOf(obj2) === null);var protoObj = {};var obj3 = { "__proto__": protoObj };assert(Object.getPrototypeOf(obj3) === protoObj); var obj4 = { __proto__: "not an object or null" };assert(Object.getPrototypeOf(obj4) === Object.prototype);assert(!obj4.hasOwnProperty("__proto__"));

Only one prototype is allowed to be changed within the object literal value. Multiple prototype changes are considered as syntactic errors.

If you do not use the attribute definition in the colon notation, the prototype of the object is not changed. Instead, it is a common attribute definition like other attributes with different names.

var __proto__ = "variable";var obj1 = { __proto__ };assert(Object.getPrototypeOf(obj1) === Object.prototype);assert(obj1.hasOwnProperty("__proto__"));assert(obj1.__proto__ === "variable");var obj2 = { __proto__() { return "hello"; } };assert(obj2.__proto__() === "hello");var obj3 = { ["__prot" + "o__"]: 17 };assert(obj3.__proto__ === 17);

Difference from JSON

JSON only supports attribute definitions in the form of "property": value syntax. Attribute names must be enclosed in double quotation marks. Attribute definitions cannot be easily written.
In JSON, attribute values only allow strings, numbers, arrays, true, false, or other JSON objects.
JSON, the value cannot be set as a function.
Date and other objects, after JSON. parse () processing, will become a string.
JSON. parse () does not process the calculated attribute name and is thrown as an error.

DefineProperty

Object. the defineProperty () method defines a new property directly on an Object, or modifies an existing property and returns this Object // use _ proto _ Object. defineProperty (obj, "key", {_ proto __: null, // No inherited attribute value: "static" // No enumerable // No retriable // No writable // as the default value}); // explicit Object. defineProperty (obj, "key", {enumerable: false, retriable: false, writable: false, value: "static"}); // reclaim the function withValue (value) of the same object) {var d = withValue. d | (withValue. d = {enumerable: false, writable: false, retriable: false, value: null}); d. value = value; return d ;}//... and... object. defineProperty (obj, "key", withValue ("static"); // If freeze is available, prevent code addition // value, get, set, enumerable, writable, retriable // to the Object prototype (Object. freeze | Object) (Object. prototype );

When and only when the attribute descriptor value is true, the property may change or be deleted from the corresponding object. The default value is false.

Enumerabletrue when and only when this attribute appears in the corresponding object enumeration attribute. The default value is false.

Attribute-related values. It can be any valid JavaScript value (value, object, function, etc ). The default value is undefined.

Writable true if and only if the value assignment operator is used to change the attribute-related values. The default value is false.

The access descriptor also has the following optional key values:

Get: A getter method provided to the property. If there is no getter, It is undefined. Method returns the value used as the property. The default value is undefined.
Set a method that provides setter for attributes. If there is no setter, It is undefined. This method will receive a new value assigned to the property as a unique parameter. The default value is undefined.

Ps: variable definition in js

In JavaScript, var is used to define any type of variables. Each variable is just a placeholder for storing data.

Var temp; // The Code defines a variable, but its type is unknown. It can store any type of value. When it is not initialized, it is stored as undefined in test.
Var temp = 2; // The Code defines a variable and initializes it directly to a numeric type.
Var temp = "javascript"; // This Code defines a variable and directly initializes the micro-string type. Single quotes and double quotation marks are acceptable, as long as they appear in pairs.

2. Scope of Variables

In Javascript, variables defined using var are in the scope of the method or function that defines the variable. That is to say, the variable defined using var is a local variable.
Example:

Function test ()
{
Var temp = "Hello, Javascript! ";
}

Test (); // create a variable and initialize it when calling the method. After the execution, the variable is destroyed.
Alert (temp); // undefined. The variable temp has been destroyed, so it is undefined ).

If you do not use var when defining a variable, the defined variable is a global variable.

Example:

Function test2 () {temp2 = "Hello, Javascript! ";} Test2 (); // when calling a method, the variable is created and initialized. After execution, the variable still exists. Alert (temp2); // Hello, Javascript! Variable value still exists

The above content is a tour of the Javascript data types introduced by xiaobian. I hope you will like it.

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.