You don ' t know JS reading notes (one)

Source: Internet
Author: User
Tags string methods

Objective

Here is a record of their own reading you don ' t know JS series of some experience, but also JavaScript a summary of their knowledge of it. High-Energy warning: the article is longer and trivial, please bring your own bench melon seeds ~

Types (Type)

Variables don ' t has types, but the values of them do.

The meaning of this sentence is: there is no type of variable, the value stored in the variable is a type. For example, if I declare a variable var a; , there a is no type information at this time. If I assign a a string a = "Hello, World" , the typeof a resulting information string represents the a type information of the value inside "Hello, World" . If I were to reassign now, a a = 0 because the type of a value stored in it has changed, the typeof a resulting information becomes correspondingly number . This is not the same as a static language, where a variable is defined as a variable, and C/C++/Java C/C++/Java each variable can only store values that match its own type.

To make a simple analogy, JavaScript the variable is like a Swiss military bag, anything can be installed, can be loaded with books, water, clothes, on the can also be installed force, kind of unlimited (general). But C/C++/Java the variable is like a purse, it was designed to charge money, so it can only be loaded with money (dedicated), if you want to install other things such as all kinds of cards, or whatever, it is necessary to put these cards also as money, this is called coercion type conversion .

Many developers would assume "undefined" and "undeclared" is roughly the same thing, but in JavaScript, they ' re quite diff Erent. Undefined is a value, a declared variable can hold. " Undeclared "means a variable has never been declared.

The meaning of this sentence is: undefined and undeclared is two completely different concepts, many people will confuse the two. In JavaScript , it undefined means that a variable has been declared, but it has not been assigned a value, and the value inside the variable is undefined . Like what:

var A;Console.log (a);//undefined

However, undeclared it indicates that a variable has never been declared, that is, before using this variable, it has never been in the previous code (declared), it is completely sudden, the read and write operation of this variable will cause the interpreter to error and stop running. Like what:

Console.log (b);//uncaught referenceerror:b is not defined (...)

Sometimes in order to determine whether a variable (for example a ) is undefined , the general practice is if(a != undefined) , but there is a problem, if a not stated? This will cause an error in the interpreter, and in order to prevent this from happening, we can use the type judgment operator typeof to make a safe judgment: the variable that is if(typeof a != undefined) typeof not declared can be handled safely and returned undefined .

VALUES (value)

Using Delete on an array value would remove that slot from the array, but even if you remove the final element, it does not Update the Length property to be careful!

By using the delete operator to delete an element in the array, the value inside the element is emptied (set undefined ), but the element (slot) is in the array, and the length of the array does not change. Like what:

var arr = [1,2,3,4,5]; delete arr[0]; // arr = [Undefinedx1, 2, 3, 4, 5]  for (var i = 1; i < arr.length; i + +)  {delete  arr[i];} // arr = [UNDEFINEDX5]

To add, suppose you want to create an array that requires all of the elements inside undefined , if you do:

var New Array (10);

Actually, it's not right. Because the resulting array does not actually have 10 slots (slot), it is empty, just its length properties 10 . If you look inside the console, you'll get the result: [undefined × 10] . To really get undefined an array of all 10 elements, you should do this:

var array = array.apply (null, {length:10});

viewing in the console array can be found [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined] , and the results obtained above are significantly different.

JavaScript strings is immutable, while arrays is quite mutable. A further consequence of immutable strings is that's none of the string methods that alter its contents can modify In-place, But rather must create and return new strings. By contrast, many of the array methods that change array contents actually does modify in place.

JavaScriptthe string is immutable (similar to C/C++ a string), and the array is mutable. The immutable effect of a string is that its method does not directly modify the contents of the string, but instead returns a new string. Unlike this, the array method can modify the content directly.

Simple scalar primitives (strings, numbers, etc.) is assigned/passed by value-copy, but compound values (objects, etc.) a Re assigned/passed by Reference-copy. References is not like references/pointers in other Languages-they ' re never pointed at other variables/references, only a t the underlying values.

The base type ( string , number , boolean ) Assignment/pass value is the value of the pass, while the mixed type ( object , array etc.) is the reference assignment/pass value that is made, and one more thing to note is that JavaScript the reference is not like a reference in another language, it is pointing to the value itself. According to one example:

var obj = {  1}; function The foo (obj)  {= {x:2//  Object {x:1}foo () function re-assigns obj, but does not change the outer definition of obj.

Native (native type)

Primitive values don ' t has properties or methods, so to access. Length or. toString () need a object wrapper around T He value. Thankfully, JS'll automatically box (aka Wrap) The primitive value to fulfill such accesses

The basic data type does not have a property or method, and .length .toString() you need an object Object to wrap the basic data type when you need to perform actions such as or on the base data type. Thankfully, it is automatically packaged in the way it is performed JavaScript .

So, for a string, we can get the length of the string directly, or we can do a lot of string methods, such as, and .indexOf() so on.

Coercion (automatic type conversion)

Automatic type conversion is more complex, in order to illustrate their respective conversion rules, I have drawn a brain map to illustrate (the picture is large, please save it in 1:1 proportion to view):

Let's talk about the two operations, and operations that will trigger the conversion of the diet type + - .

First, let's say the + operation. ecma-262#11.6.1 the addition operator (+) has the following description:

The addition operator either performs string concatenation or numeric addition. The production additiveexpression:additiveexpression + multiplicativeexpression is evaluated as follows:

  1. Let Lref is the result of evaluating additiveexpression.
  2. Let Lval be GetValue (lref).
  3. Let Rref is the result of evaluating multiplicativeexpression.
  4. Let Rval be GetValue (rref).
  5. Let Lprim be toprimitive (lval).
  6. Let Rprim be toprimitive (rval).
  7. If type (Lprim) is a string or Type (Rprim) is a string, then Return the string, which is the result of the concatenating ToString (LPR IM) followed by ToString (Rprim)
  8. Return the result of applying the addition operation to Tonumber (Lprim) and Tonumber (Rprim). See the Note below 11.6.3.

  9. NOTE 1 No hint is provided in the calls to toprimitive in steps 5 and 6. All native ECMAScript objects except Date objects handle the absence of a hint as if the hint number were given; Date objects handle the absence of a hint as if the hint String were given. Host objects may handle the absence of a hint in some other manner.

  10. NOTE 2 Step 7 differs from step 3 of the comparison algorithm for the relational operators (11.8.5), by using the Logical-or oper ation instead of the logical-and operation.

The above paragraph is obscure, probably meaning that when the add operation is performed, if the left or right operand is not the base data type ( primitive ), it will be ToPrimitive converted (The conversion process can be seen above the brain graph), so that the left and right operands are basic data types, But what if the data types are inconsistent between the left and right sides? This involves a priority problem, and the low-priority data type is actively converted to the same data type as the high-priority, and then the add operation. Their precedence relationship is: string > num > boolean , so there are two additions: string concatenation and number addition. The specific process can be seen in:

To illustrate:

1 "1" + 1; // "One" 2 true; // 2 3 true // "1true"

For the - operation is more simple, only the numeric subtraction. The description on the ecma#11.6.2 is:

The production additiveexpression:additiveexpression-multiplicativeexpression is evaluated as follows:

  1. Let Lref is the result of evaluating additiveexpression.
  2. Let Lval be GetValue (lref).
  3. Let Rref is the result of evaluating multiplicativeexpression.
  4. Let Rval be GetValue (rref).
  5. Let Lnum be Tonumber (lval).
  6. Let Rnum be Tonumber (rval).
  7. Return the result of applying the subtraction operation to Lnum and Rnum. See the note below 11.6.3.

The approximate meaning is for the left and right operands of the non-numeric type ToNumber (see above for details), then the numeric subtraction operation. The process is as follows:

To illustrate:

"1"-1; // 0 true // 0 // 0

You don ' t know JS reading notes (one)

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.