index.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // @ts-nocheck
  2. import {isString} from '../isString'
  3. import {isNumeric} from '../isNumeric'
  4. /**
  5. * 单位转换函数,将字符串数字或带有单位的字符串转换为数字
  6. * @param value 要转换的值,可以是字符串数字或带有单位的字符串
  7. * @returns 转换后的数字,如果无法转换则返回0
  8. */
  9. export function unitConvert(value: string | number): number {
  10. // 如果是字符串数字
  11. if (isNumeric(value)) {
  12. return Number(value);
  13. }
  14. // 如果有单位
  15. if (isString(value)) {
  16. const reg = /^-?([0-9]+)?([.]{1}[0-9]+){0,1}(em|rpx|px|%)$/g;
  17. const results = reg.exec(value);
  18. if (!value || !results) {
  19. return 0;
  20. }
  21. const unit = results[3];
  22. value = parseFloat(value);
  23. if (unit === 'rpx') {
  24. return uni.upx2px(value);
  25. }
  26. if (unit === 'px') {
  27. return value * 1;
  28. }
  29. // 如果是其他单位,可以继续添加对应的转换逻辑
  30. }
  31. return 0;
  32. }
  33. // 示例
  34. // console.log(unitConvert("123")); // 输出: 123 (字符串数字转换为数字)
  35. // console.log(unitConvert("3.14em")); // 输出: 0 (无法识别的单位)
  36. // console.log(unitConvert("20rpx")); // 输出: 根据具体情况而定 (根据单位进行转换)
  37. // console.log(unitConvert(10)); // 输出: 10 (数字不需要转换)