美文网首页
一行代码实现的js方法

一行代码实现的js方法

作者: PharkiLL | 来源:发表于2021-10-08 11:48 被阅读0次

1. 计算两个日期之间的天数

const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
const daysBetween = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24))
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199

2. 在中间截断字符串

const truncateStringMiddle = (string, length, start, end) => {
  return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};

console.log(
  truncateStringMiddle(
    'A long story goes here but then eventually ends!', // string
    25, // 需要的字符串大小
    13, // 从原始字符串第几位开始截取
    17, // 从原始字符串第几位停止截取
  ),
);
// A long story ... eventually ends!

3. 在结尾处截断字符串

const truncateString = (string, length) => {
  return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};

console.log(
  truncateString('Hi, I should be truncated because I am too loooong!', 36),
);
// Hi, I should be truncated because...

4. 检查用户是否在Apple设备上

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);

console.log(isAppleDevice);
// true/false

5. 随机生成字符串

const randomString = () => Math.random().toString(36).slice(2); 
console.log(randomString()); 

6. 检查对象是否为空

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

相关文章

网友评论

      本文标题:一行代码实现的js方法

      本文链接:https://www.haomeiwen.com/subject/vcqxoltx.html