JavaScript使用小技巧

JavaScript 小知识点使用

本文是一篇翻译文章,原文信息如下:

  • 原文:<45 useful="" javascript="" tips,="" tricks="" and="" best="" practices="">
  • 作者:
    JavaScript还是很多新手踏入编程世界的第一个语言。既可以用来显示浏览器中的简单提示框,也可以通过nodebot或nodruino来控制机器人。能够编写结构清晰、性能高效的JavaScript代码的开发人员,现如今已成了招聘市场最受追捧的人

    1 用JSON来序列化与反序列化

    var person = {name :’Saad’, age : 26, department : {ID : 15, name : “R&D”} };
    var stringFromPerson = JSON.stringify(person);
    / stringFromPerson 结果为 “{“name”:”Saad”,”age”:26,”department”:{“ID”:15,”name”:”R&D”}}” /
    var personFromString = JSON.parse(stringFromPerson);
    / personFromString 的值与 person 对象相同 /

2 避免使用with()

使用with()可以把变量加入到全局作用域中,因此,如果有其它的同名变量,一来容易混淆,二来值也会被覆盖。

3 传给setInterval()和setTimeout()时使用函数而不是字符串

如果传给setTimeout()和setInterval()一个字符串,他们将会用类似于eval方式进行转换,这肯定会要慢些,因此不要使用:
1 setInterval(‘doSomethingPeriodically()’, 1000);
2 setTimeout(‘doSomethingAfterFiveSeconds()’, 5000);
而是用:
1 setInterval(doSomethingPeriodically, 1000);
2 setTimeout(doSomethingAfterFiveSeconds, 5000);

4 使用switch/case代替一大叠的if/else

其实,switch/case中的case条件,还可以这样写:
function getCategory(age) {
var category = “”;
switch (true) {
case isNaN(age):
category = “not an age”;
break;
case (age >= 50):
category = “Old”;
break;
case (age <= 20):
category = “Baby”;
break;
default:
category = “Young”;
break;
};
return category;
}
getCategory(5); // 将返回 “Baby”

5 HTML字段转换函数

function escapeHTML(text) {  
var replacements= {"<": "&lt;", ">": "&gt;","&": "&amp;", "\"": "&quot;"};                      
return text.replace(/[<>&"]/g, function(character) {  
    return replacements[character];  
}); 

}

6 开发时注意代码结构,上线前检查并压缩JavaScript代码

可以使用JSLint或JSMin等工具来检查并压缩代码。

7 临时存储用于计算和查询的变量

在jQuery选择器中,可以临时存储整个DOM元素。
var navright = document.querySelector(‘#right’);
var navleft = document.querySelector(‘#left’);
var navup = document.querySelector(‘#up’);
var navdown = document.querySelector(‘#down’);

8 通过for-in循环检查对象的属性

下面这样的用法,可以防止迭代的时候进入到对象的原型属性中。
for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}

9 浮点计算的问题

1 0.1 + 0.2 === 0.3 // is false
2 9007199254740992 + 1 // is equal to 9007199254740992
3 9007199254740992 + 2 // is equal to 9007199254740994

为什么呢?因为0.1+0.2等于0.30000000000000004。JavaScript的数字都遵循IEEE 754标准构建,在内部都是64位浮点小数表示,具体可以参见JavaScript中的数字是如何编码的.

可以通过使用toFixed()和toPrecision()来解决这个问题。

10 在条件中使用逻辑与或

1 var foo = 10;
2 foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
3 foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();

11 使用length属性截断数组

前面的例子中用length属性清空数组,同样还可用它来截断数组:
1 var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
2 myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].
与此同时,如果把length属性变大,数组的长度值变会增加,会使用undefined来作为新的元素填充。length是一个可写的属性。
1 myArray.length = 10; // the new array length is 10
2 myArray[myArray.length - 1] ; // undefined

12 获取数组中的最大值和最小值

1 var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
2 var maxInNumbers = Math.max.apply(Math, numbers);
3 var minInNumbers = Math.min.apply(Math, numbers);

13 清空数组

var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].

14 数组之间追加

1 var array1 = [12 , “foo” , {name “Joe”} , -2458];
2 var array2 = [“Doe” , 555 , 100];
3 Array.prototype.push.apply(array1, array2);
4 / array1 值为 [12 , “foo” , {name “Joe”} , -2458 , “Doe” , 555 , 100] /

15 字符串去空格

Java、C#和PHP等语言都实现了专门的字符串去空格函数,但JavaScript中是没有的,可以通过下面的代码来为String对象函数一个trim函数:
1 String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, “”);};

16 javascript && Jquery 获取各种高度

IE中:
document.body.clientWidth ==> BODY对象宽度
document.body.clientHeight ==> BODY对象高度
document.documentElement.clientWidth ==> 可见区域宽度
document.documentElement.clientHeight ==> 可见区域高度
FireFox中:
document.body.clientWidth ==> BODY对象宽度
document.body.clientHeight ==> BODY对象高度
document.documentElement.clientWidth ==> 可见区域宽度
document.documentElement.clientHeight ==> 可见区域高度
Opera中:
document.body.clientWidth ==> 可见区域宽度
document.body.clientHeight ==> 可见区域高度
document.documentElement.clientWidth ==> 页面对象宽度(即BODY对象宽度加上Margin宽)
document.documentElement.clientHeight ==> 页面对象高度(即BODY对象高度加上Margin高)

alert(document.body.clientWidth); //网页可见区域宽(body)
alert(document.body.clientHeight); //网页可见区域高(body)
alert(document.body.offsetWidth); //网页可见区域宽(body),包括border、margin等
alert(document.body.offsetHeight); //网页可见区域宽(body),包括border、margin等
alert(document.body.scrollWidth); //网页正文全文宽,包括有滚动条时的未见区域
alert(document.body.scrollHeight); //网页正文全文高,包括有滚动条时的未见区域
alert(document.body.scrollTop); //网页被卷去的Top(滚动条)
alert(document.body.scrollLeft); //网页被卷去的Left(滚动条)
alert(window.screenTop); //浏览器距离Top
alert(window.screenLeft); //浏览器距离Left
alert(window.screen.height); //屏幕分辨率的高
alert(window.screen.width); //屏幕分辨率的宽
alert(window.screen.availHeight); //屏幕可用工作区的高
alert(window.screen.availWidth); //屏幕可用工作区的宽

Jquery
alert($(window).height()); //浏览器当前窗口可视区域高度
alert($(document).height()); //浏览器当前窗口文档的高度
alert($(document.body).height());//浏览器当前窗口文档body的高度
alert($(document.body).outerHeight(true));//浏览器当前窗口文档body的总高度 包括border padding margin
alert($(window).width()); //浏览器当前窗口可视区域宽度
alert($(document).width()); //浏览器当前窗口文档对象宽度
alert($(document.body).width()); //浏览器当前窗口文档body的宽度
alert($(document.body).outerWidth(true));//浏览器当前窗口文档body的总宽度 包括border padding margin

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2021 魏姣
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信