js之规范代码写法
一、避免多次定义var
例如:var a = 0;
var b = 1;
尽量定义为:var a = 0,
b =1;
二、尽量在结尾使用分号(semicolon)
否则编辑器会提示:Unterminated statement。未结束的声明;
三、循环中使用hasOwnProperty(key)
get_value: function(obj){
for(var key in obj){
if(!obj.hasOwnProperty(key)) continue;
var value = "";
if(key!="ProductUnit" && obj[key]!="ListingDuration-ali"){
value = $("#"+obj[key]).val()||undefined;
}else if(obj[key] == "ListingDuration-ali"){
value = $("[name="+obj[key]+"]:checked").val();
}else if(key == "ProductUnit"){
value = $("#"+key+" :selected").val();
}
if(value){
product[key] = value.trim();
}else{
delete product[key];
}
}
}
没有那个方法的话,会提示(不是报错):
Possible iteration over unexpected (custom / inherited) members, probably missing hasOwnProperty check less... (Ctrl+F1)
Checks for any instances of unfiltered for-in loops in JavaScript. The use of this construct results in processing inherited or unexpected properties. You need to filter own properties with hasOwnProperty() method. The validation works in JavaScript, html or jsp files.
可能的意外(自定义/遗传迭代)的成员,可能丢失hasownproperty检查少…(Ctrl + F1)
任何情况下在循环过滤JavaScript检查。在处理继承或意外属性中使用此构造结果。你需要和hasownproperty()法自身的属性过滤器。验证工作在JavaScript、HTML或JSP文件。
(翻译来自百度)
四、function functionname(){}结尾不需要分号结尾(Unnecessary semicolon)
Unnecessary semicolon less... (Ctrl+F1)
Checks JavaScript source code for unneeded semicolons . The validation works in JavaScript, html or jsp files.
五、名字被多处声明(duplicate declaration)
例如:
在if(……){var demo = "demo"}else(var demo = "demo")两个里边都定义了var demo;
六、番外篇:
String.prototype.format= function(){
var args = arguments;
return this.replace(/\{(\d+)\}/g,function(s,i){
return args[i];
});
};