68 effective ways to write high-quality JS code (i)
Get to know the JavaScript version you're using
Tips:
- Decide which versions of JavaScript your application supports.
- Make sure that the features of any JavaScript you use are supported for all environments that your application will run.
- Strict code is always tested in an environment that performs strict pattern checking.
- Beware of connecting scripts that have different expectations in different strict modes.
The popularity of JavaScript made it an international standard in 1997, with the official name ECMAScript. In addition to multiple versions of the ECMAScript standard, there are some JavaScript implementations that support non-standard features and other JavaScript implementations that do not support the situation. So pay attention to the version supported by the JavaScript code you wrote.
/*[Sample]如下代码,在IE下会Syntax error,但是在Chrome中则是定义常量*/const PI=3.14;PI=3;PI
Because of JavaScript's primary ecosystem-Web browsers do not support having programmers specify a JavaScript version to execute code. In ES5, the introduction of another version control consideration-the strict format (strict mode)-allows you to choose to disable more problematic or error-prone features in the JavaScript language in the restricted JavaScript version. Because the JS syntax involves backward compatibility, strict code can be executed in environments where there is no strict checking.
/*[Sample]如何使用严格模式,在程序/函数体的开始处加入‘use strict‘ 使用字符串字面量作为指令看起来比较怪异,但好处是可以向后兼容,因为执行字符串字面量没有任何副作用/*function f(x){ ‘use strict‘; var arguments=[];//SyntaxError:Unexpected eval or arguments in strict mode}
The "Use strict" directive only takes effect at the top of a script or function, which is also a trap using strict mode. The script connection becomes quite sensitive. If there are multiple JS files, some need to be executed in strict mode, some do not need to execute in strict mode, how to deal with it?
- Separate connections for files that require strict mode checking and files that do not require strict mode checking
- Concatenate multiple files by wrapping themselves in an immediately called function expression
/*file1.js*/function fun1(){ var arguments=[];}/*file2.js*/‘use strict‘;function fun2(){ console.log(‘strict mode!‘);}/*按照方式二连接后的文件内容应该是*//*fileMerge.js*/(function(){ function fun1(){ var arguments=[]; }})();(function(){ ‘use strict‘; function fun2(){ console.log(‘strict mode!‘); }})();
No.2, understanding the floating-point number of JavaScript
Tips:
- The numbers of JavaScript are double-precision floating-point number.
- JavaScript integers are just a subset of the double-precision floating-point numbers, not a single data type.
- A bitwise operation treats a number as a 32-bit signed integer.
- When the precision in the impatient point operation is trapped.
Most languages have several numeric data types, but JavaScript has only one
typeof 1; //‘number‘typeof 1.1; //‘number‘typeof -1; //‘number‘
For bitwise operations, JavaScript does not directly manipulate the operand as a floating-point number, and it is converted to a 32-bit integer before the operation
8|1; //98.1|1; //9
How do I quickly convert from 10 to 2~36?
(100).toString(2); //1100100(100).toString(10); //100(100).toString(35); //2u(100).toString(36); //2s
Note the use of parseint and parsefloat
Warning (The following are non-standard features, different browser execution):
- If the string to be converted starts at 0x or 0X, then parseint (' 0xAB ') is equivalent to parseint (' 0xAB ', 16)
- If 0 is encountered, then parseint (' 013 ') is equivalent to parseint (' 013 ', 8)
- It is strongly recommended that you specify the parseint when using
parseInt(‘9x‘); //9 会自动忽略不能转换的字符parseInt(‘x9‘); //NaN 发现第一个字符就不能转换,返回NaNparseInt(‘1100100‘,2); //100 可以在parseInt的第二个参数指定当前字符串的进制parseInt(‘2xxx‘,2); //NaN 遇到无法转换的情况,返回NaNparseInt(‘08‘);
The floating-point number is the name of the imprecise, you can know the following code execution results?
0.1+0.2; //0.30000000000000004(0.1+0.2)+0.3; //0.60000000000000010.1+(0.2+0.3); //0.60.3-0.2; //0.09999999999999998
When we care about precision, be careful about the limitations of floating-point numbers. An effective method is to use integer numeric operations as much as possible, and integers do not need to be rounded at the time of operation.
No.3, beware of implicit casts
Tips:
- Type errors may be hidden by implicit casts.
- The overloaded operator + is either an addition or a string connection depending on its parameter type.
- object is cast to a number by the ValueOf method and coerced to a string by the ToString method.
- An object with the ValueOf method should implement the ToString method, returning a string representation of the number produced by the valueof method.
- To test whether a value is an undefined value, you should use TypeOf or compare to undeined instead of using the truth operation.
3+true; //4 true转换为数字1‘fun‘(1); //TypeError:string is not a functionnull.x; //TypeError: Cannot read property ‘x‘ of null2+3; //52+‘3‘; //‘23‘ 偏爱字符串,遇到字符串,那么优先用字符串连接1+2+‘3‘; //‘33‘ 加法运算是从左到右,所以等价于(1+2)+‘3‘1+‘2‘+3; //‘123‘ ‘17‘*3; //51‘8‘|‘1‘ //9
How do I test if a value is Nan?
var x=NaN;x===NaN; //false,NaN不等于自身
If you know that the value with the test is a number, you can use the standard library function isNaN
isNaN(NaN); //true
However, for other values that are definitely not nan, but are coerced to Nan, using the isNaN method is indistinguishable.
isNaN(‘foo‘); //trueisNaN(undefined); //trueisNaN({}); //trueisNaN({valueOf:‘foo‘}); //true
Fortunately, there is a simple and reliable but somewhat non-intuitive way to test it:
In JS, Nan is the only value that is not equal to itself.
var x=NaN;x!==x //true/*测试x是否是NaN,是返回true,否则返回false*/function isReallyNaN(x){ return x!==x;}
How do I control the coercion of an object?
‘J‘+{toString:function(){return ‘S‘}}; //‘JS‘ 2*{valueOf:function(){return 3;}}; //6var obj={ toString:function(){ return ‘[object Obj]‘; }, valueOf:function(){ return 1; }}‘object:‘+obj; //‘object:1‘解释:1. 在需要数字的场合,优先判断valueOf,没有的话,则采用toString。2. 如果对象同时拥有valueOf和toString方法,同时又一定是需要数字的场合,那么JavaScript盲目的选择valueOf方法而不是toString方法来解决这种含糊的情况。3. 针对2:最好避免使用valueOf方法,除非对象的确需要一个数字的抽象,并且obj.toString()能产生一个obj.valueOf()的字符串的表示。
About the truth operation:
There are 7 false values in JavaScript: false, 0,-0, ', NaN, null, and undefined, others are true
No.4, primitive type better than encapsulated object
Tips:
- As an equality comparison, the encapsulated object of the original type behaves differently from its original value.
- Getting and setting properties of the original type value implicitly creates the encapsulated object.
In addition to objects, JavaScript has 5 primitive value types: Boolean values, Numbers, strings, nulls, and undefined. (Confusingly, the typeof operation for a null type results in "Object", however, the ECMAScript standard describes it as a unique type.) )
var s=‘hello‘; var sObj=new String(s);typeof s; //‘string‘typeof sObj; //‘object‘ 包装对象的类型是objectvar sObj1=new String(s);var sObj2=new String(s);sObj1==sObj2; //falsesObj1===sObj2; //false解释:可以理解为引用类型,每个对象是单独的对象,其引用是不一致的,所以只等于自身。
JavaScript has an implicit encapsulation of basic types, so we can write code like this:
‘test‘.toUpperCase(); //‘TEST‘‘test‘.test=‘test‘;‘test‘.test; //undefined解释:对基本类型调用方法/设置属性时,会产生隐式封装。原始值->封装类型(产生封装对象)->封装对象执行方法/设置属性->返回原始值->抛弃封装对象。所以更新封装不会造成持久的影响,同时对原始值设置属性是没有意义的。
No.5, avoid using the = = Operator for mixed types
Tips:
- When the parameter type is not the same, the = = operator applies a set of hard-to-understand implicit casting rules.
- Use the = = = operator so that the reader can understand your comparison operation without having to design any implicit casts.
- When comparing values of different types, use your own explicit casts to make the program's behavior clearer.
Look at the code:
‘1.0e0‘=={valueOf:function(){return true;}}; //true 因为通过隐式转换,就变成了1==1,所以结果为true。转换为字符串:‘‘+1; //‘1‘转换为数字 : +‘1‘; //1var date=new Date(‘1999/12/31‘);date==‘1991/12/31‘;//falsedate==‘Fri Dec 31 1999 00:00:00 GMT+0800 (China Standard Time)‘;//true解释:世界上有太多的数据表现形式,JS需要知道你使用的是哪一种,==运算符并不能推断和统一所有的数据格式,所以更好的策略是显式自定义应用程序转换的逻辑,并使用严格相等运算符。
JavaScript Codex: 68 Effective ways to write high-quality JS code (i) (by-law)