javascript常用的一些公共方法

获取当前时间

获取当前时间并补零的 JavaScript 方法:

function getCurrentDateTime() {
    
    
  const now = new Date();
  let year = now.getFullYear();
  let month = now.getMonth() + 1;
  let day = now.getDate();
  let hours = now.getHours();
  let minutes = now.getMinutes();
  let seconds = now.getSeconds();

  // 统一的补零方法
  const addZero = num => (num < 10 ? `0${
      
      num}` : num);

  // 补零操作
  month = addZero(month);
  day = addZero(day);
  hours = addZero(hours);
  minutes = addZero(minutes);
  seconds = addZero(seconds);

  return `${
      
      year}-${
      
      month}-${
      
      day} ${
      
      hours}:${
      
      minutes}:${
      
      seconds}`;
}

// 调用方法获取当前时间
const currentDateTime = getCurrentDateTime();
console.log(currentDateTime);

说明:使用了 JavaScript 内置的 Math.random() 函数来获取 0 到 1 之间的随机数。我们直接返回这个随机数。

获取随机数

控制位数和小数个数的获取随机数的 JavaScript 方法:

function getRandomNumber(digits, decimals) {
    
    
  const max = Math.pow(10, digits) - 1;
  const min = Math.pow(10, digits - 1);
  let randomNumber = Math.random() * (max - min + 1) + min;

  if (decimals > 0) {
    
    
    const factor = Math.pow(10, decimals);
    randomNumber = Math.floor(randomNumber * factor) / factor;
  } else {
    
    
    randomNumber = Math.floor(randomNumber);
  }

  return randomNumber;
}

// 调用方法获取随机数
const randomNumber = getRandomNumber(4, 2); // 获取一个4位数,保留2位小数的随机数
console.log(randomNumber);

说明:添加了 digitsdecimals 两个参数,分别用来控制返回的数的位数和保留的小数的个数。我们首先根据指定的位数计算出最大值和最小值,然后使用 Math.random() 函数生成一个在这个范围内的随机数。

同时,我们还判断了 decimals 参数的值,如果大于 0,说明需要保留小数,我们就使用一个因子将随机数放大一定倍数,然后取整,最后再除以因子来保留指定的小数位数。如果小于等于 0,就直接取整。

获取随机颜色

获取随机颜色的 JavaScript 方法:

function getRandomColor() {
    
    
  const letters = "0123456789ABCDEF"; // 16进制字符
  let color = "#";

  for (let i = 0; i < 6; i++) {
    
    
    color += letters[Math.floor(Math.random() * 16)];
  }

  return color;
}

// 调用方法获取随机颜色
const randomColor = getRandomColor();
console.log(randomColor);

说明:使用了 16 进制颜色表示法,颜色值由 6 个字符组成。我们定义了一个包含所有 16 进制字符的字符串,并使用循环随机选择 6 个字符,然后将这 6 个字符拼接起来,加上 # 号,就得到了一个随机颜色值。

数据处理

对传入数据进行处理的 JavaScript 公共方法:

function processData(data, decimals = 2, defaultValue = "-") {
    
    
  if (typeof data === "number") {
    
    
    return data.toFixed(decimals);
  } else if (!data && data !== 0) {
    
    
    return defaultValue;
  } else {
    
    
    return data;
  }
}

// 调用方法处理数据
const data1 = processData(3.14159); // 默认保留两位小数
const data2 = processData(3.14159, 3); // 保留三位小数
const data3 = processData(null); // 返回默认值“-”
const data4 = processData(undefined); // 返回默认值“-”
const data5 = processData("", 0); // 返回默认值“0”
const data6 = processData("hello"); // 返回原始值“hello”
console.log(data1);
console.log(data2);
console.log(data3);
console.log(data4);
console.log(data5);
console.log(data6);

说明:首先判断传入的值是否为数字。如果是数字,就调用 toFixed() 方法保留指定的小数位数,并返回结果。如果不是数字,就判断是否为空、null、undefined,如果是,就返回一个默认值,否则就返回原始值。

查找属性值

根据某个属性值查找对象并返回另一个属性值的 JavaScript 方法:

function findObjectByProperty(arr, property, value, targetProperty) {
    
    
  const targetObj = arr.find(obj => obj[property] === value);
  return targetObj ? targetObj[targetProperty] : null;
}

// 示例数据
const arr = [
  {
    
    id: 1, name: 'Tom', age: 18},
  {
    
    id: 2, name: 'Jerry', age: 21},
  {
    
    id: 3, name: 'Alice', age: 25},
  {
    
    id: 4, name: 'Bob', age: 20},
  {
    
    id: 5, name: 'Lily', age: 23},
];

// 调用方法查找对象并返回对应属性值
const targetAge1 = findObjectByProperty(arr, 'id', 3, 'age');
const targetAge2 = findObjectByProperty(arr, 'name', 'Bob', 'age');
console.log(targetAge1); // 输出 25
console.log(targetAge2); // 输出 20

说明:使用 find() 方法查找数组中指定属性名称的对象,找到后返回该对象的目标属性值。如果没有找到,则返回 null。在调用方法时,我们可以根据需要提供数组、属性名称、属性值和目标属性名称等参数。

获取字符串中的数字

获取字符串中数字的 JavaScript 方法,支持获取字符串中的两个数字:

function getNumbersFromString(str) {
    
    
  const reg = /\d+/g;
  const matches = str.match(reg);
  return matches ? matches.map(num => parseInt(num)) : [];
}

// 示例字符串
const str = '这是一个带数字123和456的字符串';

// 调用方法获取字符串中数字
const numbers = getNumbersFromString(str);
console.log(numbers); // 输出 [123, 456]

说明:使用正则表达式 /\d+/g 匹配字符串中的数字,并将匹配结果保存在 matches 数组中。然后我们使用 map() 方法将匹配到的数字转换为数字类型,并返回该数组。

获取地址栏参数

获取地址栏参数的 JavaScript 方法:

function getUrlParam(key) {
    
    
  const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
  const matches = window.location.search.substr(1).match(reg);
  return matches ? decodeURIComponent(matches[2]) : null;
}

// 示例 URL:https://www.example.com/?name=Tom&age=18

// 调用方法获取参数值
const name = getUrlParam('name');
const age = getUrlParam('age');
console.log(name); // 输出 "Tom"
console.log(age); // 输出 "18"

说明:使用正则表达式 (^|&) + key + '=([^&]*)(&|$)' 匹配地址栏中指定参数名称的参数值,并将匹配结果保存在 matches 数组中。然后我们使用 decodeURIComponent() 方法将匹配到的参数值进行解码,并返回该值。如果地址栏中没有指定参数,则返回 null。

分离对象属性

可用于将对象中的某些属性分离出来得到一个新的对象的公共 JavaScript 方法:

function extractProperties(obj, keys) {
    
    
  return keys.reduce((acc, key) => {
    
    
    if (obj.hasOwnProperty(key)) {
    
    
      acc[key] = obj[key];
    }
    return acc;
  }, {
    
    });
}

const obj = {
    
     name: '小明', age: 18, gender: 'male' };
const extractedObj = extractProperties(obj, ['name', 'age']);

console.log(extractedObj); // { name: '小明', age: 18 }

说明:将传入的 obj 对象中指定的属性 keys 分离出来得到一个新的对象,并返回该新对象。其中,obj 为需要被处理的对象,keys 为一个数组,包含了需要被提取到新对象中的属性名。

猜你喜欢

转载自blog.csdn.net/Serena_tz/article/details/129797560