Skip to content

Instantly share code, notes, and snippets.

@NinoFocus
Created February 16, 2012 05:59
Show Gist options
  • Save NinoFocus/1842479 to your computer and use it in GitHub Desktop.
Save NinoFocus/1842479 to your computer and use it in GitHub Desktop.
JavaScript 惯用法和技巧
// 检测空串
if (!$.trim(str)) {
}
// 字符串/数字类型转换
var str = '100';
var num = str - 0;
var str2 = num + '';
// 空检则
if (!value) { // undefined, null, false, 0, '', NaN 等为 '空'
}
// 逻辑或 ||
if (!a) {
a = 100;
}
a = a || 100; // 注意 不能写成 a ||= 100, 虽然ruby支持
if (!this.elm) {
this.elm = $('#mydiv');
}
this.elm = this.elm || $('#mydiv');
var pageSize = 10;
if (data && data.pageSize) {
pageSize = data.pageSize;
}
pageSize = (data || {}).pageSize || 10;
// 逻辑与&&
function(success) {
if (success) {
success('abc');
}
success && success('abc'); 
}
// 注意: 不能写成 options.delay && this.delay = true; 赋值运算附优先级低
// 可以是 options.delay && (this.delay = true);
// 默认参数
function hello(options) {
options = $.extend({
time: 1000,
color: '#f00',
'font-size': '12px'
}, options);
...
}
// 字符串拼接
var html = [];
for (...) {
html.push('...');
}
html = html.join('');
// 字符串模板
var template =
'<div>\
<dl>\
<dt>示例1</dt>\
<dd></dd>\
<dt></dt>\
<dd></dd>\
</dl>\
</div>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment