js 常用处理函数

107 阅读1分钟

判断字符串是否是json字符串

const isJsonString = (str: string) => {
  try {
    const toObj = JSON.parse(str); // json字符串转对象
    if (toObj && typeof toObj === 'object') {
      return true;
    }
  } catch {}
  return false;
};

字符串的字符间添加空格

const addSpace = (str) => str.split('').join(' ');

trim()去除字符串首尾的空格

"   hello   ".trim();

eval() 计算表达式的结果

eval(1+1)

js 判断对象是否为空

// 使用 `Object.keys()` 方法判断对象是否有可枚举的属性;
const isObjectEmpty = (obj) => Object.keys(obj).length === 0;

// 使用 `JSON.stringify()` 将对象转换为字符串,然后判断字符串是否为空;
const isObjectEmpty = (obj) => JSON.stringify(obj) === '{}';

// 使用 `for...in` 循环判断对象是否有属性;
const isObjectEmpty = (obj) => {
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            return false;
        }
    }
    return true;
}
// Object.getOwnPropertyNames()获取到对象中的全部属性名,存到一个数组中;
const isObjectEmpty = (obj) => Object.getOwnPropertyNames(obj).length === 0;

// 使用 `for...in` 循环判断对象是否有属性;
const isObjectEmpty = (obj) => {
    for (let key in obj) {
        return false;
    }
    return true;
}

js 获取数组中元素最大值

// 使用内置的 Math.max 函数;
let numbers = [1, 2, 3, 4, 5];
let max = Math.max(...numbers);
console.log(max); // 输出: 5

// 在不支持ES6扩展运算符的环境下工作,你可以使用`apply`方法;
let numbers = [1, 2, 3, 4, 5];
let max = Math.max.apply(null, numbers);
console.log(max); // 输出: 5

数组扁平化 flat()

let arr = [1, 2, [2, 3, 4, [2, 1], 2, [2, 3]]];
let a = arr.flat();
console.log(a); // [ 1, 2, 2, 3, 4, [ 2, 1 ], 2, [ 2, 3 ] ];

let b = arr.flat(2);
console.log(b); // [1, 2, 2, 3, 4, 2, 1, 2, 2, 3];