gpt4 book ai didi

javascript - 这个 prettyDate 函数是如何工作的?好像它有多个返回值

转载 作者:行者123 更新时间:2023-11-30 17:39:30 25 4
gpt4 key购买 nike

我在改编 John Resig 的 prettyDate 函数的 Smashing Node 一书中看到了这段代码片段。我不明白函数如何返回一个字符串,当它显然是一个 bool 值时。

Date.prototype.__defineGetter__('ago', function () {
var diff = (((new Date()).getTime() - this.getTime()) / 1000)
, day_diff = Math.floor(diff / 86400);
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" ||
Math.ceil( day_diff / 7 ) + " weeks ago";
});

var a = new Date('11/05/1989');
console.log(a.ago); // outputs '1264 weeks ago'

最佳答案

运算符 ||&& 在 Javascript 中不严格返回 bool 值。

x ||如果 y 为真,则求值为 x,否则为 y;如果 x && y 为假,则计算结果为 x,否则为 y。因此它们都可以产生任何类型的值。

你会看到这种类型的用法在几个场景中使用,例如为参数分配默认值,例如:

// not the best example, but makes the point
function increment(i, step) {
return i + (step || 1);
}

甚至

function firstNonZero(a, b, c) {
return a || b || c || null;
}

关于javascript - 这个 prettyDate 函数是如何工作的?好像它有多个返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21370209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com