判断字符串是否是json字符串
const isJsonString = (str: string) => {
try {
const toObj = JSON.parse(str);
if (toObj && typeof toObj === 'object') {
return true;
}
} catch {}
return false;
};
字符串的字符间添加空格
const addSpace = (str) => str.split('').join(' ');
trim()去除字符串首尾的空格
" hello ".trim();
eval() 计算表达式的结果
eval(1+1)
js 判断对象是否为空
const isObjectEmpty = (obj) => Object.keys(obj).length === 0;
const isObjectEmpty = (obj) => JSON.stringify(obj) === '{}';
const isObjectEmpty = (obj) => {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
const isObjectEmpty = (obj) => Object.getOwnPropertyNames(obj).length === 0;
const isObjectEmpty = (obj) => {
for (let key in obj) {
return false;
}
return true;
}
js 获取数组中元素最大值
let numbers = [1, 2, 3, 4, 5];
let max = Math.max(...numbers);
console.log(max);
let numbers = [1, 2, 3, 4, 5];
let max = Math.max.apply(null, numbers);
console.log(max);
数组扁平化 flat()
let arr = [1, 2, [2, 3, 4, [2, 1], 2, [2, 3]]];
let a = arr.flat();
console.log(a);
let b = arr.flat(2);
console.log(b);