My personal blog: http://www.xiaolongwu.cn
In peacetime development, coding skill is very important, will let you write a lot less code, play a more effective effect.
Here is a summary of a few simple skills, you learn together
1. Convert string to Integer using + 、-、/1,*1
This method is used to convert a number of string types to an integer type, and if a letter returns Nan.
var a = "1234", b = "leonWuv";//我们想把a转换为1234的整数型,一般方法console.log(typeof Number(a)) //number//简单写法console.log(+a + 1,typeof +a); //1235 numberconsole.log(a - 0 + 1,typeof (a-0)); //1235 numberconsole.log(a*1 + 1,typeof (a*1)); //1235 numberconsole.log(a/1 + 1,typeof (a/1)); //1235 numberconsole.log(b/1 + 1,typeof (b/1)); //NaN number
This is also used for date (); it returns a timestamp
//以下方法都返回时间戳console.log(+ new Date()); //1512378253218 2017年12月04日17时左右;console.log(Date.parse(new Date())); //1512378253000 注意后三位向下取整为000;console.log(new Date("2017/1/1").getTime()); ////1483200000000
2, use!! Cast Boolean value
We need to verify if a variable exists or is valid, can use!! To make a quick and easy judgment.
This trick I have in JavaScript data type do you get it? Absolute Dry Goods The fourth part of this blog post mentions
In summary, it is: As long as the value of the variable is: 0, NULL, "", Undefined, or Nan will return false, and the return is true. Look at the following example
var a = 0,b = "12";console.log(!!c); //false// 分解上面的代码--Boolean(c)得false,取非为true,再取非为false。console.log(!!d) //true// 分解上面的代码--Boolean(d)true,取非为false,再取非为true
3. When iterating through an array, the length of the cache array
When dealing with an array loop, many of us usually write this.
for(var i = 0; i < array.length; i++) { console.log(array[i]);}
This is possible when we traverse a small array, but when we work with a large array, this writes the length of the array each time the loop is computed, and there is a delay, so we can write
var length = array.length;for(var i = 0; i < length; i++) { console.log(array[i]);}
Of course we can also write this, both of these ways are possible
for(var i = 0, length = array.length; i < length; i++) { console.log(array[i]);}
4. Rational use of && operators
Look at this piece of code.
if(a){ console.log("hello leonWu"); //解释一下这段代码,如果Boolean(a)为true,就打印出hello leonWu}
Let's modify the above code a little bit.
a && console.log("hello leonWu"); //结果是一样的,但是这样是不是简单清晰多了,代码量也少了
RELATED links: Practical tips for JS coding (II.)
Not to be continued ....
GitHub resource address: Practical tips for Https://github.com/js coding (i). MD
My personal blog: http://www.xiaolongwu.cn
CSDN Blog Address: https://blog.csdn.net/wxl1555
If you have doubts or doubts about the content of my blog, please leave a comment in the comments section below, or e-mail me to learn progress together.
Email:[email protected]
JS Foundation Advanced--the practical technique of compiling (I.)