Home > Web Front-end > JS Tutorial > body text

Knowledge points of JavaScript that are easily overlooked

php中世界最好的语言
Release: 2018-03-14 10:01:11
Original
1527 people have browsed it

This time I will bring you knowledge points about javaScript that are easily overlooked. What are the precautions about javaScript that are easily overlooked. The following is a practical case, let’s take a look.

1. Get all the keys of the object:

var arr = ['a', 'b', 'c'];Object.keys(arr ); //["0","1","2"]var obj={name:Jack,age:12}Object.keys(obj)//["name","age"]Object.getOwnPropertyNames(obj)
Copy after login

2. The attributes and methods of the function

name attribute: return immediately following the function The function name after the keyword.

function f1() {}
f1.name // 'f1'var f2 = function () {};
f2.name // ''var f3 = function myName() {};
f3.name // 'myName'
Copy after login

length attribute: Returns the number of parameters expected to be passed in by the function, that is, the number of parameters in the function definition.

function f(a, b) {}
f.length // 2
Copy after login

The toString method of the function returns the source code of the function.

function f() {
  a();
  b();
  c();
}
f.toString()// function f() {//  a();//  b();//  c();// }
Copy after login

3. Usually, the most common occasion for eval is to parse JSON data strings, but the correct approach should be to use the JSON.parse method provided by the browser

4.Bit operator is used to directly calculate binary bits, there are 7 in total.

Or operation (or): The symbol is |, which means that if both binary bits are 0, the result is 0, otherwise it is 1.

And operation (and): The symbol is &, which means that if both binary bits are 1, the result is 1, otherwise it is 0.

No operation (not): The symbol is ~, which means inverting a binary bit.

Exclusive OR operation (xor): The symbol is ^, which means that if the two binary bits are not the same, the result is 1, otherwise it is 0.

Left shift operation (left shift): The symbol is <<.
The left shift operator means to move the binary value of a number to the left by the specified number of digits, with 0 at the end, that is, multiplied by the specified power of 2 (the highest bit, the sign bit, does not participate in the move).

// The binary form of 4 is 100, // Shifting one position to the left is 1000 (that is, 8 in decimal) // This is equivalent to multiplying by 2 raised to the power of 4 << 1// 8- 4 << 1// -8

Right shift operation (right shift): The symbol is >>.
The right shift operator means to move the binary value of a number to the right by the specified number of digits, padding the head with 0, that is, dividing by the specified power of 2 (the highest bit, the sign bit, does not participate in the movement).

4 & gt; & gt; 1 // 2/*
// Because the binary form of 4 is 00000000000000000000000000000100,
// One person to get 0000000000000000000000001010,
// is a decimal 2
*/-4 >> 1// -2/*
// Because the binary form of -4 is 11111111111111111111111111111100,
// Shift one bit to the right, add 1 to the head, and get 11111111111111111111111111111110,
// is the decimal -2
*/

right shift operation with sign bit (zero filled right shift): the sign is >>>
This operator means moving the binary form of a number to the right, including the sign bit, and adding 0 to the head. Therefore, this operation always returns a positive value. For positive numbers, the result of this operation is exactly the same as the right shift operator (»). The main difference is that for negative numbers

4 >>> 1// 2-4 >>> 1/ / 2147483646/*
// Because the binary form of -4 is 1111111111111111111111111111100,
// Shift the sign bit right by one bit, and get 011111111111111111111111111110,
// is 21 in decimal 47483646.
*/

5. JavaScript’s native error type

SyntaxError is a syntax error that occurs when parsing code.

// 变量名错误var 1a;// 缺少括号console.log &#39;hello&#39;);
Copy after login

ReferenceError is an error that occurs when referencing a variable that does not exist.

unknownVariable// ReferenceError: unknownVariable is not definedconsole.log() = 1// ReferenceError: Invalid left-hand side in assignmentthis = 1// ReferenceError: Invalid left-hand side in assignment
Copy after login

RangeError is an error that occurs when a value exceeds the valid range. There are several main situations, one is that the array length is a negative number, the other is that the method parameters of the Number object are out of range, and the function stack exceeds the maximum value.

new Array(-1)// RangeError: Invalid array length(1234).toExponential(21)// RangeError: toExponential() argument must be between 0 and 20

TypeError is an error that occurs when a variable or parameter is not of the expected type. For example, if you use the new command on primitive types such as strings, Boolean values, and numerical values, this error will be thrown because the parameter of the new command should be a constructor.

new 123//TypeError: number is not a funcvar obj = {};
obj.unknownMethod()// TypeError: obj.unknownMethod is not a function
Copy after login

URIError is an error thrown when the parameters of URI-related functions are incorrect, mainly involving encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent(), escape() and unescape() these six functions.

decodeURI(&#39;%2&#39;)// URIError: URI malformed
Copy after login

When the eval function is not executed correctly, an EvalError will be thrown. This error type no longer appears in ES5 and is only retained to ensure compatibility with previous code.

6. Customized Error

function UserError(message) {   this.message = message || "默认信息";   this.name = "UserError";
}
UserError.prototype = new Error();
UserError.prototype.constructor = UserError;
Copy after login

The above code customizes an error object UserError and lets it inherit the Error object. Then, you can generate this custom error.

new UserError("This is a custom error!");

7.JavaScript programming style

Indentation
Select spaces or tab keys for indentation, You can only choose one type and do not mix them up. If you add a project midway, follow the style in the original program.

Block
The curly brackets at the beginning of the block should not start on a new line, but should immediately follow the block, as shown below:

block{
    ···
}
Copy after login

Pencils

Indicates that when the function is called, there is no space between the function name and the left bracket.

means that when the function is defined, there is no space between the function name and the left bracket.

其他情况时,前面位置的语法元素与左括号之间,都有一个空格。

行尾的分号
建议不要省略

全局变量
JavaScript最大的语法缺点,可能就是全局变量对于任何一个代码块,都是可读可写。这对代码的模块化和重复使用,非常不利。
因此,避免使用全局变量。如果不得不使用,用大写字母表示变量名,比如UPPER_CASE。

变量声明
JavaScript会自动将变量声明”提升”(hoist)到代码块(block)的头部。

if (!o) {  var o = {};
}// 等同于var o;if (!o) {
  o = {};
}
Copy after login

为了避免可能出现的问题,最好把变量声明都放在代码块的头部。

for (var i = 0; i < 10; i++) {  // ...}// 写成var i;for (i = 0; i < 10; i++) {  // ...}
Copy after login

另外,所有函数都应该在使用之前定义,函数内部的变量声明,都应该放在函数的头部。

new命令
JavaScript使用new命令,从构造函数生成一个新对象。

var o = new myObject();
Copy after login

上面这种做法的问题是,一旦你忘了加上new,myObject()内部的this关键字就会指向全局对象,导致所有绑定在this上面的变量,都变成全局变量。
因此,建议使用Object.create()命令,替代new命令。如果不得不使用new,为了防止出错,最好在视觉上把构造函数与其他函数区分开来。比如,构造函数的函数名,采用首字母大写(InitialCap),其他函数名一律首字母小写。

with语句
禁止使用with语句。

相等和严格相等
不要使用“相等”(==)运算符,只使用“严格相等”(===)运算符。

语句的合并
有些程序员追求简洁,喜欢合并不同目的的语句。比如,原来的语句是

a = b;if (a) {  // ...}```
Copy after login

他喜欢写成下面这样。

if (a = b) {
// ...
}
Copy after login

虽然语句少了一行,但是可读性大打折扣,而且会造成误读,让别人误解这行代码的意思是下面这样。

```if (a === b){  // ...}```
Copy after login

建议不要将不同目的的语句,合并成一行。
- 自增和自减运算符
自增(++)和自减(--)运算符,放在变量的前面或后面,返回的值不一样,很容易发生错误。事实上,所有的++运算符都可以用+= 1代替。

- switch…case结构switch...case结构要求,在每一个case的最后一行必须是break语句,否则会接着运行下一个case。这样不仅容易忘记,还会造成代码的冗长。
而且,switch...case不使用大括号,不利于代码形式的统一。此外,这种结构类似于goto语句,容易造成程序流程的混乱,使得代码结构混乱不堪,不符合面向对象编程的原则。

function doAction(action) {
switch (action) {
case &#39;hack&#39;:
return &#39;hack&#39;;
break;
case &#39;slash&#39;:
return &#39;slash&#39;;
break;
case &#39;run&#39;:
return &#39;run&#39;;
break;
default:
throw new Error(&#39;Invalid action.&#39;);
}
}
Copy after login

上面的代码建议改写成对象结构。

function doAction(action) {
var actions = {
&#39;hack&#39;: function () {
return &#39;hack&#39;;
},
&#39;slash&#39;: function () {
return &#39;slash&#39;;
},
&#39;run&#39;: function () {
return &#39;run&#39;;
}
};
if (typeof actions[action] !== &#39;function&#39;) {
throw new Error(&#39;Invalid action.&#39;);
}
return actionsaction;
}```
Copy after login

建议避免使用switch...case结构,用对象结构代替。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Javascript的策略模式

用JS实现排序算法

The above is the detailed content of Knowledge points of JavaScript that are easily overlooked. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template