有人可以解释一下John Resig的pretty.js JavaScript是如何工作的吗? [英] Can somebody explain how John Resig's pretty.js JavaScript works?
问题描述
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 );
});
};
prettyDate()
方法到底是怎样的?返回一个字符串?这是你在JavaScript中可以做的那些奇怪事情中的另一个还是我只是遗漏了什么?
How exactly is the prettyDate()
method returning a string? Is this another one of those 'strange' things you can do in JavaScript or am I just missing something?
编辑:我没有问他是如何返回一个值,我问他是如何返回一个字符串。
edit: I didn't ask how he's returning a value, I asked how he's returning a string.
return day_diff == 0&& (....)
以我用过的任何语言返回一个布尔值。
return day_diff == 0 && (....)
returns a boolean in any language I've ever used.
推荐答案
它在那里说: return ...
然后进入一个长嵌套列表,基本上是内联 ifs
。 ; - )
It says right there: return ...
and then goes into a long nested list of basically "inline ifs
". ;-)
在Javascript中,布尔运算符返回其中一个操作数的值,而不仅仅是 true
或 false
。例如。 0 || 'foo'
返回'foo'
。该特性与操作员短路一起使用。 false&& true
不会评估 true
并立即返回 false
,因为整个表达式必须是 false
。
In Javascript, the boolean operators return the value of one of the operands, not just true
or false
. E.g. 0 || 'foo'
returns 'foo'
. This characteristic is used in conjunction with operator short-circuiting. false && true
will not evaluate the true
side and return false
immediately, since the whole expression must be false
.
这篇关于有人可以解释一下John Resig的pretty.js JavaScript是如何工作的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!