hello,小伙伴们你们好。最近在一些网站上看到关于一行代码的文章,感觉非常有意思就整理了一些发出来和你们一起分享。
数组去重
const numbers = [1, 2, 3, 2, 2, 3, 4, 4, 1];
console.log([...new Set(numbers)]);
从数组中过滤所有虚值
const myArray = [1, undefined, null, 2, NaN, true, false, 3];
console.log(myArray.filter(Boolean));
将字符串转换为数字
const str = "123";
const num = +str;
console.log(typeof num);
将数字转换为字符串
const num = 123;
console.log(num + "");
使用 && 符号简写条件判断语句
// 普通写法
if (condition) {
doSomething();
}
// 简写
condition && doSomething();
function Goods(name, price) {
this.name = name;
this.price = price;
}
滚动到页面顶部
const goToTop = () => window.scrollTo(0, 0);
goToTop();
将RGB转化为十六机制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); console.log(rgbToHex(26, 38, 55));
好了,今天就先分享到这里了,觉得有用的话就点个赞吧!