这篇文章主要介绍13个使用一行JavaScript代码实现的程序,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
该函数使用Math.random()
方法返回一个布尔值(true
或者 false
)。Math.random创建一个0到1之间的随机数,我们只要检查它是否高于或低于0.5,就有50%机会得到true或false。
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
使用这种方法,我们能够检查在函数中提供的日期是否是工作日或周末的日子。
const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 7, 6)));
// true 因为是周五
console.log(isWeekday(new Date(2021, 7, 7)));
// false 因为是周六
有几种不同的方法来反转一个字符串。这是最简单的一种,使用split()、reverse()和join()方法。
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// 'dlrow olleh'
Document.hidden
(只读属性)返回布尔值,表示页面是(true
)否(false
)隐藏。
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
场外:无意间发现爱奇艺广告播放时间居然是在当前标签页激活的时候才会进行倒计时,离开当前标签页的时候,倒计时停止,百度一下发现document.hidden
这个东东。
document.hidden
是h6新增加api使用的时候有兼容性问题。
var hidden
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
}
console.log("当前页面是否被隐藏:" + document[hidden])
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// true
console.log(isEven(3));
// false
const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// "17:30:00"
console.log(timeFromDate(new Date()));
// 打印当前的时间
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// 事例
toFixed(25.198726354, 1); // 25.1
toFixed(25.198726354, 2); // 25.19
toFixed(25.198726354, 3); // 25.198
toFixed(25.198726354, 4); // 25.1987
toFixed(25.198726354, 5); // 25.19872
toFixed(25.198726354, 6); // 25.198726
我们可以使用document.activeElement
属性检查一个元素是否当前处于焦点。
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// 如果在焦点中返回true,如果不在焦点中返回 false
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// 如果支持触摸事件,将返回true,如果不支持则返回false。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
const goToTop = () => window.scrollTo(0, 0);
goToTop();
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// 2.5
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
// 事例
celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0
以上是“13个使用一行JavaScript代码实现的程序”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。