JavaScript Small details dot list (2)

Source: Internet
Author: User
Tags array length bitwise operators object object pow

Break statements and Continue statements

Both the break statement and the continue statement have a jump effect, which allows the code to be executed in an existing order.

The break statement is used to jump out of a code block or loop.

var i = 0;while(i < 100) {  console.log(‘i 当前为:‘ + i);  i++;  if (i === 10) break;}

The continue statement terminates the loop immediately, returning to the head of the loop structure and starting the next round of loops.

var i = 0;while (i < 100){  i++;  if (i % 2 === 0) continue;  console.log(‘i 当前为:‘ + i);}

Note that in addition to the Break,continue statement, there is a return statement that returns from the called function to the key function to continue execution, which can be returned with a return value specified by the argument following return. The function ends after return, and the subsequent statement is no longer executed.

Tag (label)

The JavaScript language allows the statement to be preceded by a label (label), equivalent to a locator, to jump anywhere in the program, the label can be any identifier, but not a reserved word, the statement part can be any statement.

Tags are typically used in conjunction with break statements and continue statements to jump out of a specific loop.

top:  for (var i = 0; i < 3; i++){    for (var j = 0; j < 3; j++){      if (i === 1 && j === 1) break top;      console.log(‘i=‘ + i + ‘, j=‘ + j);    }  }// i=0, j=0// i=0, j=1// i=0, j=2// i=1, j=0
Variable lift (hoisting)
    1. Hoisting is scoped to the function scope. I understand that the function scope has not been mentioned here, but it is possible to mention a note to the reader, and then link to the scope of the section to further explore;

    2. "Hoisting is only var valid for declared variables," not necessarily. The promotion of variable declarations is not all hoisting, and JavaScript has four ways to get declarations to be promoted within scope (by priority):

-language-defined declarations, such as this and arguments. You cannot redefine a variable called this in the scope because this is a language auto-defined declaration, and it has the highest priority, that is, it is hoisting to the top, and no one can overwrite it.

-Formal parameters. Although we do not need to use Var to modify formal parameters, but the formal parameters are also variables, and is automatically promoted to sub-high priority

-function declaration. In addition to Var, function declaration can also define a new name, and also be hoisting to the top of the scope, after the first two

-Finally, the general variables mentioned in this article, which are variables declared by Var

Integers and floating-point numbers

Inside JavaScript, all numbers are stored as 64-bit floating-point number, even if the integer is the same. So, 1 and 1.0 are the same and are the same number.

This means that there is no integer at the bottom of the JavaScript language, and all numbers are decimals (64-bit floating point number). What is confusing is that some operations can only be done with integers, when JavaScript automatically turns 64-bit floating-point numbers into 32-bit integers and then operations.

Because the floating-point number is not an exact value, the comparison and operation involving decimals should be particularly careful.

0.1 + 0.2 === 0.3// false0.3 / 0.1// 2.9999999999999996(0.3 - 0.2) === (0.2 - 0.1)// false

The accuracy can be up to 53 bits, which means that the absolute value is less than or equal to 2 of the 53-square integer, that is, 253 to 253, which can be represented precisely.

Math.pow(2, 53)// 9007199254740992 Math.pow(2, 53) + 1// 9007199254740992Math.pow(2, 53) + 2// 9007199254740994Math.pow(2, 53) + 3// 9007199254740996Math.pow(2, 53) + 4// 9007199254740996

In the above code, the result of an integer operation begins with an error after the 53-second party is greater than 2. Therefore, the value of 53 times greater than 2 can not maintain accuracy. Since 2 of the 53 is a decimal value of 16 bits, the simple rule is that JavaScript can handle the decimal number of 15 bits precisely.

Math.pow(2, 53)// 9007199254740992// 多出的三个有效数字,将无法保存9007199254740992111// 9007199254740992000

According to the standard, the exponent portion of the 64-bit floating-point number is 11 bits, which means that the maximum value of the exponent part is 2047 (2 11-time minus 1). That is, the exponent portion of a 64-bit floating-point number is a maximum of 2047, and half of the value is negative, then JavaScript can represent a range of 21024 to 2-1023 (open interval), which is beyond the range.

If a number is greater than or equal to 2 of the 1024, then a "forward overflow", that is, JavaScript cannot represent such a large number, will return infinity.

Math.pow(2, 1024) // InfinityMath.pow(2, -1075) // 0
parseint ()

For those numbers that would automatically turn to scientific notation, parseint would treat the notation of scientific notation as a string, leading to some strange results.

parseInt(1000000000000000000000.5) // 1// 等同于parseInt(‘1e+21‘) // 1parseInt(0.0000008) // 8// 等同于parseInt(‘8e-7‘) // 8

The parseint method can also accept the second parameter (between 2 and 36), which represents the binary of the parsed value, and returns the decimal number corresponding to that value. By default, the second parameter of parseint is 10, which is the default decimal-to-decimal.

parseInt(‘1000‘, 2) // 8parseInt(‘1000‘, 6) // 216parseInt(‘1000‘, 8) // 512
Isfinite ()

The Isfinite method returns a Boolean value that represents whether a value is a normal value.

isFinite(Infinity) // falseisFinite(-Infinity) // falseisFinite(NaN) // falseisFinite(-1) // true
With statement

It is useful when manipulating multiple properties of the same object to provide some ease of writing.

var obj = {  p1: 1,  p2: 2,};with (obj) {  p1 = 4;  p2 = 5;}// 等同于obj.p1 = 4;obj.p2 = 5;

Note that if there is a variable assignment inside the With block, it must be a property that already exists for the current object, otherwise it will create a global variable of the current scope.

var obj = {};with (obj) {  p1 = 4;  p2 = 5;}obj.p1 // undefinedp1 // 4
Bitwise operators

Binary or operator (or): the symbol is |, indicating that if two bits are 0, the result is 0, otherwise 1.
The binary and Operator (and): symbol is &, indicating that if two bits are 1, the result is 1, otherwise 0.
Binary no Operator (not): the symbol is ~, which indicates an inverse to a bits.
XOR operator: The symbol is ^, indicating that if two bits are different, the result is 1, otherwise 0.
Left shift operator: << symbol
Right shift operator: >> symbol
Right shift operator with sign bit (zero filled r shift): symbol >>>

void operator

The function of the void operator is to execute an expression and then return no value, or return undefined.

Here is a more practical example, the user clicks the link to submit the form, but does not produce a page jump.

<a href="javascript: void(document.form.submit())">  提交</a>
The function of parentheses

Parentheses are not operators, but rather a syntactic structure. There are two ways to use it: one is to put the expression in parentheses, to raise the priority of the operation, and the other is to follow the function, which is to call the function.

Number (Object)

The simple rule is that when the parameter of the number method is an object, Nan is returned, unless it is an array that contains a single numeric value.

Number({a: 1}) // NaNNumber([1, 2, 3]) // NaNNumber([5]) // 5

This is because the conversion rules behind number are more complex.

The first step is to call the ValueOf method of the object itself. If a value of the original type is returned, the number function is used directly on the value and no further steps are made.

In the second step, if the ValueOf method returns an object, the ToString method of the object itself is called instead. If the ToString method returns a value of the original type, the number function is used for that value, and no further steps are made.

In the third step, if the ToString method returns an object, an error is returned.

String (Object)

The argument to the string method returns a type string if it is an object, or a string form of the array if it is an array.

String({a: 1}) // "[object Object]"String([1, 2, 3]) // "1,2,3"

The conversion rules behind the string method are basically the same as the number method, except that the ValueOf method and the ToString method's execution order are swapped.

The ToString method of the object itself is called first. If a value of the original type is returned, the string function is used for the value, and the following steps are no longer performed.

If the ToString method returns an object, then the ValueOf method of the original object is called. If the ValueOf method returns a value of the original type, the string function is used for that value, and the following steps are no longer performed.

If the ValueOf method returns an object, an error is returned.

Native error type
    • SyntaxErrorobject is a syntax error that occurs when parsing code.

    • ReferenceErrorAn object is an error that occurs when a variable that does not exist is referenced.

    • angeErrorobject is an error that occurs when a value is outside a valid range. There are several main cases, one is the array length is negative, the second is the number object's method parameter out of range, and the function stack exceeds the maximum value.

    • TypeErrorAn object is an error that occurs when a variable or parameter is not the expected type. For example, using the new command for values of primitive types, such as strings, booleans, and numeric values, throws this error because the parameters of the new command should be a constructor.

    • URIErrorobject is an error that is thrown when the parameters of a URI-related function are incorrect, mainly involving encodeURI (), decodeURI (), encodeURIComponent (), decodeURIComponent (), Escape (), and unescape () of these six functions.

    • evalThe Evalerror error is thrown when the function is not executed correctly. The error type is no longer in use and is only retained to ensure compatibility with previous code.

var err1 = new Error(‘出错了!‘);var err2 = new RangeError(‘出错了,变量超出有效范围!‘);var err3 = new TypeError(‘出错了,变量类型无效!‘);err1.message // "出错了!"err2.message // "出错了,变量超出有效范围!"err3.message // "出错了,变量类型无效!"
Finally code block

The Try...catch structure allows a finally code block to be added at the end, indicating that the last run statement is required, regardless of whether an error occurs.

function cleansUp() {  try {    throw new Error(‘出错了……‘);    console.log(‘此行不会执行‘);  } finally {    console.log(‘完成清理工作‘);  }}cleansUp()// 完成清理工作// Error: 出错了……
Map ()

The map method can be used not only for arrays, but also for strings to iterate through each character of a string. However, it cannot be used directly, but is used indirectly through the call method of the function, or the string is first converted to an array and then used.

var upper = function (x) {  return x.toUpperCase();};[].map.call(‘abc‘, upper)// [ ‘A‘, ‘B‘, ‘C‘ ]// 或者‘abc‘.split(‘‘).map(upper)// [ ‘A‘, ‘B‘, ‘C‘ ]

Other arrays-like objects (such as the Document.queryselectorall method returns a collection of DOM nodes) can also be traversed using the method above.

The map method can also accept the second parameter, which represents the object that this is pointing to when the callback function executes.

var arr = [‘a‘, ‘b‘, ‘c‘];[1, 2].map(function(e){  return this[e];}, arr)// [‘b‘, ‘c‘]

If the array has an empty space, the map method's callback function will not execute at this location, and will skip the empty spaces of the group.

Array(2).map(function (){  console.log(‘enter...‘);  return 1;})// [, ,]
Reduce (), reduceright ()

The reduce method and the Reduceright method sequentially process each member of the array and eventually accumulate to a value.

The difference is that reduce is handled from left to right (from the first member to the last member), Reduceright from right to left (from the last member to the first member), and the others are exactly the same.

The first parameter of both methods is a function. The function accepts the following four parameters.

Cumulative variable, default is the first member of an array
The current variable, which defaults to the second member of the array
Current position (starting from 0)
Original array

[1, 2, 3, 4, 5].reduce(function(x, y){  console.log(x, y)  return x + y;});// 1 2// 3 3// 6 4// 10 5//最后结果:15
Object.keys (), Object.getownpropertynames ()

Both the Object.keys method and the Object.getownpropertynames method are used to traverse the properties of the object.

The argument to the Object.keys method is an object that returns an array. The members of the array are all property names of the object itself (not inherited).

The Object.getownpropertynames method is similar to Object.keys and accepts an object as a parameter, returning an array containing all the property names of the object itself.

For general objects, Object.keys () and Object.getownpropertynames () return the same results. Only non-enumerable properties are involved, and there is a different result. The Object.keys method returns only enumerable properties, and the Object.getownpropertynames method also returns non-enumerable property names.

var a = [‘Hello‘, ‘World‘];Object.keys(a) // ["0", "1"]Object.getOwnPropertyNames(a) // ["0", "1", "length"]

JavaScript Small details dot list (2)

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.