js 判斷是否為空的代碼如下:
// var a = "";
// var a = " ";
// var a = null;
// var a = undefined;
// var a = [];
// var a = {};
// var a = NaN;
if(a === undefined) { // 只能用 === 運算來測試某個值是否是未定義的
console.log("為undefined");
}
if(a == null) { // 等同於 a === undefined || a === null
console.log("為null");
}
// String
if(a == "" || a == null || a == undefined){ // "",null,undefined
console.log("為空");
}
if(!a){ // "",null,undefined,NaN
console.log("為空");
}
if(!$.trim(a)){ // "",null,undefined
console.log("為空");
}
// Array
if(a.length == 0){ // "",[]
console.log("為空");
}
if(!a.length){ // "",[]
console.log("為空");
}
// Object {}
if($.isEmptyObject(a)){ // 普通對象使用 for...in 判斷,有 key 即為 false
console.log("為空");
}
JavaScript程序是由若干語句組成的,語句是編寫程序的指令。JavaScript提供了完整的基本編程語句,它們是:
賦值語句、switch選擇語句、while循環語句、for循環語句、for each循環語句、do...while循環語句、break循環中止語句、continue循環中斷語句、with語句、try…catch語句、if語句(if..else,if…else if…)。