ITPub博客

首页 > IT职业 > IT生活 > JavaScript tips and tricks - 5

JavaScript tips and tricks - 5

IT生活 作者:yaweche 时间:2021-09-09 09:41:57 0 删除 编辑

Fast string concatenation
We always use + to concatenate small strings into a large one, which is considered to be a good practice.
But there will be a major hit on performance if you do many string concatenation operations on IE browser.
Consider these two comparison examples:

var startTime = new Date();var str = '';for (var i = 0; i 

var startTime = new Date();
var arr = [];
for (var i = 0; i   arr.push(i);
}
var str = arr.join(”);
alert(new Date() - startTime); // Firefox - 38ms, IE7 - 280ms
Firefox seems to do some optimization on + operator, while IE is like a stupid guy.

The unary + operator

In JavaScript it is possible to use the + operator alone before a single element.
This indicates a math operation and tries to convert the element to a number.
If the conversion fails, it will evaluate to NaN.

See some example:

2 + '1'; // "21"2 + ( +'1'); // 3

The unary + operator, when used on types other than string, will internally attempt to call valueOf() or toString() (in that order) and then attempt to convert the result to a number.

+new Date; // 1242616452016+new Date === new Date().getTime(); // true+new Date() === Number(new Date) // true

Refer to this article.

encodeURI() and encodeURIComponent()
The encodeURI method returns an encoded URI, which does not encode the following characters: “:”, “/”, “;”, and “?”.
The encodeURIComponent is designed to encode these characters.
Let’s see it in action:

'index.jsp?page='+encodeURI('/page/home.jsp');  // "index.jsp?page=/page/home.jsp"'index.jsp?page='+encodeURIComponent('/page/home.jsp');  // "index.jsp?page=%2Fpage%2Fhome.jsp"

The encodeURIComponent() method should be used in most case when encoding a single component of a URI.

table.innerHTML in IE
It’s a convenience to set element content via innerHTML property.
For example:

 
document.getElementById('container1').innerHTML = "HelloWorld!";

But setting table.innerHTML causes error in IE:

 
document.getElementById('table1').innerHTML = " Hello World! ";// works well in Firefox, but fail to work in IE

Actually, the innerHTML property of the TABLE,THEAD, TR, SELECT elements in IE are read-only.
How to build a table dynamically?

 
document.getElementById('table1').innerHTML = "
Hello World!
";

0.1+0.2 != 0.3
JavaScript treat decimals as floating point numbers, which may cause rounding errors.

0.1 + 0.2; // 0.30000000000000004

You can round it off as follows:

(0.1 + 0.2).toFixed(); // "0"

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4257/viewspace-2806214/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    0
  • 访问量
    970