js常用的技巧1-1

1.reduce 找出总和、最小值和最大值

const array  = [5,4,7,8,9,2];
array.reduce((a,b) => a+b);
// 求和输出: 35
array.reduce((a,b) => a>b?a:b);
//求最大值 输出: 9
array.reduce((a,b) => a<b?a:b);
//求最小值 输出: 2

2.时间格式化(时分秒)

const timeFromDate = date => date.toTimeString().slice(0, 8);

timeFromDate(new Date(2021, 11, 2, 12, 30, 0));  // 12:30:00
timeFromDate(new Date());  // 返回当前时间 09:00:00

3.查找日期位于一年中的第几天

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date());   // 307

4. 计算两个日期之间的间隔

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)

dayDif(new Date("2021-11-3"), new Date("2022-2-1"))  // 90

5.将十进制转换为二进制或十六进制

//在解决问题的同时,我们可以使用一些内置的方法,例如.toPrecision()或.toFixed()来实现许多帮助功能。

const num = 10;

num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"

6.空合并算子

//空合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为空或未定义时返回其右侧操作数,否则返回其左侧操作数。

const foo = null ?? 'my school';
// 输出: "my school"

const baz = 0 ?? 42;
// 输出: 0

二、字符串处理

1. 字符串首字母大写

//该方法用于将英文字符串的首字母大写处理:

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("hello world")  // Hello world

2. 翻转字符串

//该方法用于将一个字符串进行翻转操作,返回翻转后的字符串:

const reverse = str => str.split('').reverse().join('');

reverse('hello world');   // 'dlrow olleh'

3. 随机字符串

//该方法用于生成一个随机的字符串:

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

randomString();

4. 截断字符串

//该方法可以从指定长度处截断字符串:

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

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

5. 去除字符串中的HTML

//该方法用于去除字符串中的HTML元素:

const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';

6.单行回文检查

//检测字符正序和倒序是否相等


function   checkPalindrome(str){
    return    str==str.split('').reverse().jion('')
}

checkPalindrome('naman');
// 输出: true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值