http://ejohn.org/files/pretty.js
// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
return;
return day_diff == 0 && (
diff < 60 && "just now" ||
diff < 120 && "1 minute ago" ||
diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
diff < 7200 && "1 hour ago" ||
diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days ago" ||
day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
jQuery.fn.prettyDate = function(){
return this.each(function(){
var date = prettyDate(this.title);
if ( date )
jQuery(this).text( date );
});
};
Run Code Online (Sandbox Code Playgroud)
该prettyDate()方法返回字符串究竟是怎么回事?这是你在JavaScript中可以做的那些"奇怪"事情中的另一个还是我只是遗漏了什么?
编辑:我没有问他是如何返回一个值,我问他是如何返回一个字符串.
return day_diff == 0 && (....) 以我曾经使用的任何语言返回布尔值.
Way*_*ett 28
在JavaScript中:
a || b 相当于 a ? a : b a && b 相当于 a ? b : a 有了这些知识,return语句的逻辑变得相当简单.
例如,假设 day_diff = 5
然后逐步采取上述声明:
return day_diff == 0 && (
diff < 60 && "just now" ||
diff < 120 && "1 minute ago" ||
diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
diff < 7200 && "1 hour ago" ||
diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days ago" ||
day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
Run Code Online (Sandbox Code Playgroud)
首先,day_diff == 0将评估false和右侧:
(diff < 60 && "just now" ||
diff < 120 && "1 minute ago" ||
diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
diff < 7200 && "1 hour ago" ||
diff < 86400 && Math.floor( diff / 3600 ) + " hours ago")
Run Code Online (Sandbox Code Playgroud)
......没有评估.双方:
day_diff == 1 && "Yesterday"
Run Code Online (Sandbox Code Playgroud)
......评估false.接下来是:
day_diff < 7 && day_diff + " days ago"
Run Code Online (Sandbox Code Playgroud)
在此表达式day_diff < 7求值为true,因此将评估其右侧(字符串)并返回其结果.
进一步阅读:
http://www.ejball.com/EdAtWork/2005/02/19/JavaScriptBooleanOperators.aspx
dec*_*eze 10
它在那里说:return ...然后进入一个基本上"内联ifs" 的长嵌套列表.;-)
在Javascript中,布尔运算符返回其中一个操作数的值,而不仅仅是true或false.例如0 || 'foo'返回'foo'.该特性与操作员短路一起使用.false && true不会评估true方并false立即返回,因为整个表达必须是false.
你是一个Java人吗?因为如果是这样你可能认为if(x)需要x是一个布尔值,而"x && y"返回一个布尔值.它不适用于JavaScript和许多其他语言,如Perl.在许多弱类型语言中,&&称为保护运算符和|| 被称为默认运算符.他们返回了两个论点中的一个.
| 归档时间: |
|
| 查看次数: |
2145 次 |
| 最近记录: |