外观
CodeSnippet-JS
箭头函数
let sayHi = () => alert("Hello!"); //无参数:
let sum = (a, b) => a + b; //等价 let sum = function(a, b) { return a + b;};
let sum = (a, b) => { // 花括号打开多线功能
let result = a + b;
return result; // 如果我们使用花括号,使用返回来获得结果
};时间
时间格式化
//const formatYmd = (date) => date.toISOString().slice(0, 10);
new Date().toISOString().slice(0, 10);
//formatYmd(new Date()); // 2020-05-06获得年月日时分秒
new Date().toISOString().split(/[^0-9]/).slice(0, -1);
// ['2022', '06', '11', '09', '53', '16', '808']数组
获取数组中随机几项
const randomItems = (arr, count) => arr.concat().reduce((p, _, __, arr) => (p[0] < count ? [p[0] + 1, p[1].concat(arr.splice((Math.random() * arr.length) | 0, 1))] : p), [0, []])[1];
//randomItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // [4, 8, 5]
//randomItems(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 4); // ['e', 'c', 'h', 'j']数组去重
const nums = [1, 2, 2, 3, 1, 2, 4, 5, 4, 2, 6];
[...new Set(nums)] // [1, 2, 3, 4, 5, 6]for循环
for (let prop in ['a', 'b', 'c'])
console.log(prop); // 0, 1, 2 (in 数组的索引)
for (let prop of ['a', 'b', 'c'])
console.log(prop); // a, b, c (of 数组值)
['a', 'b', 'c'].forEach(
val => console.log(val) // a, b, c (array values)
);序列化指定字段
const user = {
id: 1234,
username: 'johnsmith',
name: 'John Smith',
age: 39
};
JSON.stringify(user, ['username', 'name']);
// '{ "username": "johnsmith", "name": "John Smith" }'字符串
随机字符串
const randomString = () => Math.random().toString(36).slice(2);展开语法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr2, ...arr1];
// arr1 is now [3, 4, 5, 0, 1, 2]检查是否是数字
const isNumber = (value) => !isNaN(parseFloat(value)) && isFinite(value);