赞
踩
CSDN话题挑战赛第2期
参赛话题:学习笔记
目录
今天给大家分享js实用的代码片段,值得收藏!
- const randomStr = () => Math.random().toString(20).slice(2);
- randomStr();
输出结果:
- const reverseStr = str => str.split('').reverse().join('');
- reverseStr('vue 入门到精通');
- reverseStr('IT技术分享社区');
输入结果:
- const set=new Set([5,7,1,3,4,2,5,6,8]);
- console.log([...set]);
- const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
- rgbToHex(255, 255, 255);
- const shuffle = array => array.sort(() => 0.5-Math.random());
- shuffle([29,3,57,2,40])
输出结果
- const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
- dayDif(new Date("2022-09-03"), new Date("2022-11-15"))
输出结果
- const dayOfYearStr = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
- dayOfYearStr(new Date());
截取字符串长度,超过部分显示为 ...
- const splitStr= (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;
- splitStr('vue is good web frame', 7)
- splitStr('vue is good web frame', 10)
- const isNotEmptyArr = arr => Array.isArray(arr) && arr.length > 0;
- isNotEmptyArr([6,66,666]);
- isNotEmptyArr([]);
- const merge = (a, b) => a.concat(b);
- const a=[1,2,3];
- const b=[4,5,6];
- merge(a,b);
输出结果
实现英文句子中,每个单词首字母大写
- const capitalizeEveryWordStr = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
- capitalizeEveryWordStr('hello vue js ');
给定的数组从左边开始删除 n 个元素,默认n=1
- const dropArr = (arr, n = 1) => arr.slice(n);
- dropArr([10, 20, 30 , 40]);
- dropArr([10, 20, 30 , 40], 2);
- dropArr([10, 20, 30 , 40], 42);
输出结果:
- const getTimeFromDate = date => date.toTimeString().slice(0, 8);
- getTimeFromDate(new Date());
输出结果:
- const isJson = str => {
- try {
- JSON.parse(str);
- return true;
- } catch (e) {
- return false;
- }
- };
- isJson('{"name":"小明","address":"苏州"}');
- isJson('{"name":"小王",address:"南京"}');
输出结果:
- const currentURL = () => window.location.href;
- currentURL();
输出结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。