20+个JavaScript单行代码

转自:https://mp.weixin.qq.com/s/8UcIu0BzMk3Tnf5QtjOIxA

  • 01.随机获取布尔值
const getRandomBoolean = () => Math.random() >= 0.5;
console.log(getRandomBoolean());
// a 50/50 chance of returning true or false
  • 02.检查日期是否是周末
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;

console.log(isWeekend(new Date(2021, 4, 14)));
// false (Friday)
console.log(isWeekend(new Date(2021, 4, 15)));
// true (Saturday)
  • 03.检查数字是偶数还是奇数
const isEven = (num) => num % 2 === 0;

console.log(isEven(5));
// false
console.log(isEven(4));
// true
  • 04.获取数组中的唯一值(数组去重)
const uniqueArr = (arr) => [...new Set(arr)];

console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]
  • 05.检查变量是否是数组
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

  • 06.在两个数字之间生成一个随机数
    这将以两个数字为参数,并将在这两个数字之间生成一个随机数!
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

console.log(random(1, 50));
// could be anything from 1 - 50
  • 07.生成随机字符串(唯一ID?)
const randomString = () => Math.random().toString(36).slice(2);

console.log(randomString());
// could be anything!!!
  • 08.滚动到页面顶部
const scrollToTop = () => window.scrollTo(0, 0);

scrollToTop();
  • 09.切换布尔
// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
//or
const toggleBool = b => !b;
  • 10.交换两个变量
[foo, bar] = [bar, foo];
  • 11.计算两个日期之间的天数
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);

console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199
  • 12.将文字复制到剪贴板
const copyTextToClipboard = async (text) => {
  await navigator.clipboard.writeText(text);
};
  • 13.-合并多个数组的不同方法
    有两种合并数组的方法。其中之一是使用concat方法。另一个使用扩展运算符(…)。

PS:我们也可以使用“设置”对象从最终数组中复制任何内容。

// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];

// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
  • 14.获取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
  • 15.在结尾处截断字符串
  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...
  • 16.从中间截断字符串
    uploading-image-180316.png
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!
  • 17.大写字符串
  const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
  console.log(capitalize('hello world'));
  • 18.检查当前选项卡是否在视图/焦点内
const isTabInView = () => !document.hidden;  // Not hidden

isTabInView();
  • 19.检查用户是否在Apple设备上
  const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);

console.log(isAppleDevice);
// true/false
  • 20.三元运算符
// Longhand
const age = 18;
let greetings;

if (age < 18) {
  greetings = 'You are not old enough';
} else {
  greetings = 'You are young!';
}

// Shorthand
const greetings = age < 18 ? 'You are not old enough' : 'You are young!';
  • 21.短路评估速记
// Longhand
if (name !== null || name !== undefined || name !== '') {
  let fullName = name;
}

// Shorthand
const fullName = name || 'buddy';
“fool me once,shame on you. fool me twice, shame on me.”,翻译过来的意思是“愚弄我一次,是你坏;愚弄我两次,是我蠢”。
原文地址:https://www.cnblogs.com/newcapecjmc/p/14975411.html