01-随机获取布尔值
Math.random创建一个介于0和1之间的随机数,然后我们检查它是否大于或小于0.5。
这意味着有50/50的机会会得到对或错。
const getRandomBoolean = () => Math.random() >= 0.5;
02-检查日期是否为周末
通过此功能,你将能够检查提供的日期是工作日还是周末。
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;
console.log(isWeekend(new Date(2021, 7, 3)));
// false (星期五)
console.log(isWeekend(new Date('2021-7-4'.replace(/-/g,'/'))));
// true (星期六)
03-检查数字是偶数还是奇数
简单的实用程序功能,用于检查数字是偶数还是奇数。
const isEven = (num) => num % 2 === 0; console.log(isEven(5)); // false console.log(isEven(4)); // true
04-检查变量是否为数组
一种检查变量是否为数组的干净简便的方法。
当然,也可以有其他方法
const isArray = (arr) => Array.isArray(arr);
console.log(isArray([1, 2, 3]));
// true
console.log(isArray({ name: 'Ovi' }));
// false
console.log(isArray('Hello World'));
// false
05-在两个数字之间生成一个随机数
这将以两个数字为参数,并将在这两个数字之间生成一个随机数!
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min); console.log(random(1, 50));
06-生成随机字符串(唯一ID?)
也许你需要临时的唯一ID,这是一个技巧,你可以使用它在旅途中生成随机字符串。
const randomString = () => Math.random().toString(36).slice(2); console.log(randomString());
07-滚动到页面顶部
所述window.scrollTo()方法把一个X和Y坐标滚动到。
如果将它们设置为零和零,我们将滚动到页面顶部。
const scrollToTop = () => window.scrollTo(0, 0); scrollToTop();
08-计算两个日期之间的天数
要计算两个日期之间的天数,
我们首先找到两个日期之间的绝对值,然后将其除以86400000(等于一天中的毫秒数),最后将结果四舍五入并返回。
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2021-07-01'), new Date('2021-07-25')));
// 24
09-获取javascript语言的实际类型
人们有时会使用库来查找JavaScript中某些内容的实际类型,这一小技巧可以节省你的时间(和代码大小)。
const trueTypeOf = (obj) => {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function
10-在结尾处截断字符串
需要从头开始截断字符串,这不是问题!
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...
11-从中间截断字符串
从中间截断字符串怎么样?
该函数将一个字符串作为第一个参数,然后将我们需要的字符串大小作为第二个参数,然后从第3个和第4个参数开始和结束需要多少个字符
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!
12-开头大写字符串
好吧,不幸的是,JavaScript没有内置函数来大写字符串,但是这种解决方法可以实现。
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('hello world'));
// Hello world