Home Web Front-end JS Tutorial Knowledge points of JavaScript that are easily overlooked

Knowledge points of JavaScript that are easily overlooked

Mar 14, 2018 am 10:01 AM
javascript js Knowledge points

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles