一、JavaScript小技巧

來源:互聯網
上載者:User

標籤:

1.聲明變數時別忘記 var

2.相等比較請用 === 而不是 ==

3.undefined、null、0、false、NaN、‘‘(Null 字元串)都是假值行末加封號

3.小心使用 typeof、instanceof 以及 constructor
JavaScript原型鏈和instanceof運算子的曖昧關係
typeof和instanceof簡介及用法
javascript中prototype、constructor以及__proto__之間的三角關係
IIFE。 參考 (譯)詳解javascript立即執行函數運算式(IIFE)

4.擷取數組的任一元素
var items = [12, 548 , ‘a‘ , 2 , 5478 , ‘foo‘ , 8852, , ‘Doe‘ , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];

5.擷取某一範圍內的任一數值
var x = Math.floor(Math.random() * (max - min + 1)) + min;

6.產生 0~max 的數組 ([0, 1, 2 ... max])
var a = [], max = 100;
for (var i = 0; a.push(i++) <= max; );

7.產生任意長度字串(字元包括 a-z 0-9)
function generateRandomAlphaNum(len) {
var rdmString = "";
for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.substr(0, len);
}

8.數組亂序
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(function(){ return Math.random() - 0.5});
有一個比 sort 更好的辦法(Fisher-Yates shuffle),具體可以參考 discuss

9.string trim
String.prototype.trim = function(){return this.replace(/^s+|s+$/g, "");};

9.在一個數組後附加一個數組
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */

10.把偽數組轉為數組
var argArray = Array.prototype.slice.call(arguments);

11.判斷數字
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}

12.判斷數組 see Javascript中判斷數組的正確姿勢
①擷取數組最值
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);

②清空數組
var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].
刪除數組元素請不要用 delete,而是用 splice

③截取數組
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

④小數保留(注意,toFixed 方法返回 string 值)
var num =2.443242342;
num = num.toFixed(4); // num will be equal to 2.4432

⑤浮點數問題
0.1 + 0.2 === 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994

⑥用 for-in 檢查對象屬性
for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}

⑦逗號運算子
var a = 0;
var b = ( a++, 99 );
console.log(a); // a will be equal to 1
console.log(b); // b is equal to 99

⑧快取資料(避免查詢相同 DOM 多次)
var navright = document.querySelector(‘#right‘);
var navleft = document.querySelector(‘#left‘);
var navup = document.querySelector(‘#up‘);
var navdown = document.querySelector(‘#down‘);

⑨使用 isFinite() 方法前先檢查參數
isFinite(0/0) ; // false
isFinite("foo"); // false
isFinite("10"); // true
isFinite(10); // true
isFinite(undefined); // false
isFinite(); // false
isFinite(null); // true !!!

13.JSON 序列化和還原序列化
var person = {name :‘Saad‘, age : 26, department : {ID : 15, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString is equal to person object */

14.避免使用 eval() 和 Function() 建構函式 。為了避免雙重求值,see 高效能JavaScript 編程實踐
避免使用 with
避免用 for-in 遍曆數組元素
setInterval() setTimeout() 的參數請使用函數,而不是字串。避免雙重求值,同上。
使用 switch-case 而不是一長串的 if-else。這點有待考證,The Good Part 中說要盡量不使用 switch-case 語句。

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

15.避免在迴圈中使用 try-catch-finally
這樣寫是不好的:
var object = [‘foo‘, ‘bar‘], i;
for (i = 0, len = object.length; i <len; i++) {
try {
// do something that throws an exception
}
catch (e) {
// handle exception
}
}
應該這樣:
var object = [‘foo‘, ‘bar‘], i;
try {
for (i = 0, len = object.length; i <len; i++) {
// do something that throws an exception
}
}
catch (e) {
// handle exception
}

16.AJAX 佈建要求逾時(setTimeout 佈建要求逾時中止 AJAX)
var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
clearTimeout(timeout);
// do something with response data
}
}
var timeout = setTimeout( function () {
xhr.abort(); // call error callback
}, 60*1000 /* timeout after a minute */ );
xhr.open(‘GET‘, url, true);
xhr.send();

一、JavaScript小技巧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.