使用JavaScript一行代码实现程序

使用JavaScript将隐藏手机号中间4位数字

var str='13888888888';  
var str2 = str.substr(0, 3) + "****" + str.substr(7);
var str3 = str.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');

滚动到页面顶部

const goToTop = () => window.scrollTo(0, 0);
goToTop();

反转字符串

const reverse = str => str.split('').reverse().join('');
reverse('hello world');     
// 'dlrow olleh'

检查当前标签是否隐藏

Document.hidden (只读属性)返回布尔值,表示页面是(true)否(false)隐藏。

const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();

场外:无意间发现爱奇艺广告播放时间居然是在当前标签页激活的时候才会进行倒计时,离开当前标签页的时候,倒计时停止,百度一下发现document.hidden这个东东。

document.hiddenh5新增加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()));
// 打印当前的时间

保留 n 位小数

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

检查当前浏览器是否支持触摸事件

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 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

检查当前是否有元素处于焦点中

我们可以使用document.activeElement属性检查一个元素是否当前处于焦点。

const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// 如果在焦点中返回true,如果不在焦点中返回 false

......后续补充

posted @   AvenCheung  阅读(35)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示