js 之中常用快速处理方法

js之中骚操作语法

把字符串类型直接转化为 布尔类型

  • 执行思路:+ ‘0’ 转化为num类型 -> !! 双重否定 直接把num类型转化为bool类型
!!+0 -> false
!!+'0' -> false
!!+1 -> true
!!+'1' -> true

把对象的属性值设置为空

      let obj = { a:"aaa", b:"bbb", c:"ccc"};
      Object.keys(obj).forEach(key=>{obj[key]=''})
      console.log("obj", obj); // obj {a: '', b: '', c: ''}

把日期替换为字符串格式

("2021-01-12").replace(/\-/g, "")
'20210112'

js处理 url

const url = 'http://example.com/index.html?a=1&b=2&c=3&d=true'
const res = getQueryString(url)
console.log('res', res) // res {a: '1', b: '2', c: '3', d: 'true'}

function getQueryString(url: any) {
  const idx = url.indexOf('?')
  const urlParam = url.substr(idx + 1, url.length)
  let urlObj = {}
  let urlObjItem = urlParam.length ? urlParam.split('&') : [] // 取得每一个参数项,
  let item = null
  let len = urlObjItem.length
  for (let i = 0; i < len; i++) {
    item = urlObjItem[i].split('=')
    var name = decodeURIComponent(item[0]),
      value = decodeURIComponent(item[1])
    if (name) {
      urlObj[name] = value
    }
  }
  return urlObj
}

js 之中常用的快速技巧方法

格式化input输入框

限制input只能输入正整整

<template>
    value - {{ value }}
    <a-input placeholder="请输入" v-model.trim="value" @input="limitInpNum()" />
</template>
export default {
  name: "About2",
  components: {},
  data() {
    return {
      value: "",
    };
  },
  methods: {
    // 限制input只能输入整数
    limitInpNum() {
      // console.log("this.value前", this.value); //this.value前 11e
      let res = /^\d*$/.test(this.value);
      if (!res) this.value = this.value.replace(/[^\d]/g, "");
      // console.log("this.value后", this.value); //this.value前 11
    },
  },
};

日期相关

选中当前时间的上一天

    // 获取前一天的日期
    getTodayDate() {
      let date2 = new Date(new Date(new Date().toLocaleDateString()).getTime());
      let year = date2.getFullYear();
      let momth = date2.getMonth() + 1;
      momth = momth < 10 ? "0" + momth : momth;
      let date = date2.getDate() - 1;
      date = date < 10 ? "0" + date : date;
      return year + "-" + momth + "-" + date;
    },

1680254063618 毫秒 处理时间 17分钟 || 20小时 20天

        // 处理时间 17分钟 || 20小时 20天
        dealTimeNum(timestamp) {
            // console.log('timestamp', timestamp);
            let res = '';
            let date = new Date(Number(timestamp));
            let now = new Date();
            let diff = now.getTime() - date.getTime(); // 获取两个日期对象之间的毫秒差
            let days = Math.floor(diff / (1000 * 60 * 60 * 24)); // 将毫秒差转换为天数
            let hours = Math.floor(diff / (1000 * 60 * 60)); // 将毫秒差转换为小时
            let minute = Math.floor(diff / (1000 * 60)); // 将毫秒差转换为分钟
            let second = Math.floor(diff / (1000)); // 将毫秒差转换为秒
            // console.log('days', days, 'hours', hours, 'minute', minute);
            if (days > 0) {
                res = days + '天';
            } else if (hours > 0) {
                res = hours + '小时';
            } else if (minute > 0) {
                res = minute + '分钟';
            } else if (second > 0) {
                res = minute + '秒';
            }
            // console.log('res', res);
            return res;
        }

数组相关

数组的最大值 & 最小值

    let arr = [100,888,2,5555,33,-111,7];
    let max = Math.max.apply(null,arr);
    let min = Math.min.apply(null,arr)
    console.log('max',max,"min",min); // test.html:13 max 5555 min -111

	let Data=[
        {city:'w',收入:16.5},
        {city:'x',收入:14.5},
        {city:'e',收入:17.5},
        {city:'a',收入:1.5},
        {city:'y',收入:31.5},
    ]
   let arr=[];
    for(let i=0;i<Data.length;i++){
        arr.push(Data[i]['收入']);
    }
    var max=Math.max(...arr);
    console.log(max)// 31.5

数组的去重

    let res = [1,222,333,555,1,222,99,33]
    let res1 = res.reduce(function (pre, cur) {
      return (pre.indexOf(cur) === -1) ? pre.concat(cur) : pre //满足pre这个数组的属性,有属于这个条件的时候,就返回到新数组内
    }, [])
    console.log('res1', res1); // [1, 222, 333, 555, 99, 33]

数组对象去重

const arr = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Charlie' },
  { id: 3, name: 'David' },
  { id: 2, name: 'Eve' }
];

const uniqueArr = Array.from(new Set(arr.map(item => item.id)))
  .map(id => arr.find(item => item.id === id));

console.log(uniqueArr);
// Output: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'David' }]


    const arr = [{ name: 1, value: 1 }, { name: 1 }, { name: 2 }];

    const uniqueArr = arr.filter(
      (item, index, self) => index === self.findIndex((t) => t.name === item.name),
    );

    console.log('uniqueArr', uniqueArr);

求数组的总和(元素为对象 -> 累计对象中的金额属性)

  let arr = [ { val:1 }, { val:2} ]
  let sum = arr.reduce(function (pre, cur) {
   return pre + cur.val* 1;
 }, 0);
 // sum 为3

字符串相关

判断 某个字符串是否包含另一个字符串

  • !== -1 证明找得到该字符串
let str = "123"
console.log(str.indexOf("2") != -1); // true

数组的交集

      const a = [{ id: 1, a: 123, b: 1234 }, { id: 2, a: 123, b: 1234 }]
      const b = [{ id: 1, a: 123, b: 1234 }, { id: 2, a: 123, b: 1234 }, { id: 3, a: 123, b: 1234 }, { id: 4, a: 123, b: 1234 }]
      const arr2 = [...b].filter(x => [...a].some(y => y.id === x.id))
      console.log('arr2', arr2) // [ {id: 1, a: 123, b: 1234},{id: 2, a: 123, b: 1234}]

数组交集 a和b数组 a若有check为true则修改b的check为true,其余的修改为false

      // let a = [{ id: 1, check: true}, { id: 2,check: true}];
      // let b = [{ id: 1, check: true }, { id: 2, check: true }, { id: 3, check: true }, { id: 4, check: true }];
      // b.forEach(itemB => {
      //   itemB.check = a.some(itemA => itemA.id === itemB.id) ? true : false;
      // });
      // console.log(b); // [{ id: 1, check: true }, { id: 2, check: true }, { id: 3, check: false}, { id: 4, check: false}];

个人信息相关

从身份证号码中解析出生日期

/**
 * 从身份证号码中解析出生日期
 * @param certNo
 * @returns {string} YYYY-MM-DD的格式
 */
export function resolveBirthdayFromCertNo(certNo) {
  try {
    var birthday
    if (certNo) {
      certNo = certNo.toString()
      if (certNo.length === 15) {
        // 15位身份证,第7、8位为出生年份(两位数),第9、10位为出生月份,第11、12位代表出生日期
        birthday = '19' + certNo.substring(6, 8) + '-' + certNo.substring(8, 10) + '-' + certNo.substring(10, 12)
      } else if (certNo && certNo.length === 18) {
        // 18位身份证,第7、8、9、10位为出生年份(四位数),第11、第12位为出生月份,第13、14位代表出生日期
        birthday = certNo.substring(6, 10) + '-' + certNo.substring(10, 12) + '-' + certNo.substring(12, 14)
      }
    }
    return birthday
  } catch (e) {
    console.error(e)
  }
}

校验相关

密码校验

/**
 * 密码校验
 * 至少1个大写字母English letter,(?=.*?[A-Z])
 * 至少1个小写英文字母,(?=.*?[a-z])
 * 至少1位数字,(?=.*?[0-9])
 * 至少有1个特殊字符,(?=.*?[#?!@$%^&*-])
 * 最小8个长度.{8,}
 * @param str
 * @returns {boolean}
 */
export function validatePassword(str) {
  const reg = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-,.;':"]).{8,}$/
  return reg.test(str)
}

处理 tree数据 扁平化tree 或者 一维数组转化为tree数据

tree数据 扁平化 为一维数组

  created() {
    const treeData = [
      {
        path: 'home',
        title: '首页',
        com: 'Home'
      },
      {
        path: 'about',
        title: '关于',
        children: [
          {
            path: 'about1',
            title: '关于1',
            children: [
              {
                path: 'about11',
                title: '关于11',
                com: 'About11'
              },
              {
                path: 'about12',
                title: '关于12',
                com: 'About12'
              }
            ]
          },
          {
            path: 'about2',
            title: '关于2',
            com: 'About2'
          }
        ]
      },
      {
        path: 'user',
        title: '用户',
        children: [
          {
            path: 'user1',
            title: '用户1',
            children: [
              {
                path: 'user11',
                title: '用户11',
                com: 'User11'
              },
              {
                path: 'user12',
                title: '用户12',
                com: 'User12'
              }
            ]
          },
          {
            path: 'user2',
            title: '用户2',
            com: 'User2'
          }
        ]
      }
    ]
    const res = this.treeToOneArr(treeData)
    console.log('res', res, 'treeData', treeData)
  },
  methods: {
    treeToOneArr(arr) {
      const data = JSON.parse(JSON.stringify(arr)) // 对传入的参数进行深拷贝
      const newData = [] // 创建空数组用来接收操作后的新数组
      const hasChildren = item => {
        // 递归遍历,把包含children的选项拿出来,push到之前新建的空数组内
        (item.children || (item.children = [])).map(v => {
          hasChildren(v)
        })
        delete item.children // 删除原children属性,可选项
        newData.push(item)
      }
      data.map(v => hasChildren(v))
      return newData
    },
  }

在这里插入图片描述

  • 扁平化数据 方法2
    treeToArray(tree) {
      var res = []
      for (const item of tree) {
        const { child, ...i } = item
        if (child && child.length) {
          res = res.concat(this.treeToArray(child))
        }
        res.push(i)
      }
      return res
    }

一维数组 组合 为 tree数据

  created() {
    const treeData = [
      { 'id': 6, 'title': '首页', 'leave': 1, 'order': 1, 'parent_id': 0, 'url': '/home' },
      { 'id': 1, 'title': '物业管理', 'leave': 1, 'order': 1, 'parent_id': 0, 'url': '/estate1' },
      { 'id': 2, 'title': '费用管理', 'leave': 2, 'order': 1, 'parent_id': 1, 'url': 'estate' },
      { 'id': 3, 'title': '临时收费', 'leave': 3, 'order': 1, 'parent_id': 2, 'url': 'charge' },
      { 'id': 4, 'title': '物业费', 'leave': 3, 'order': 2, 'parent_id': 2, 'url': 'propertyFees' },
      { 'id': 5, 'title': '关于', 'leave': 1, 'order': 1, 'parent_id': 0, 'url': '/about' }
    ]
    const res = this.treeData(treeData)
    console.log('res', res, 'treeData', treeData)
  },
  methods: {
    treeData(data) {
    // 对源数据深度克隆
      const cloneData = JSON.parse(JSON.stringify(data))
      // filter嵌套filter相当于for循环嵌套for循环
      const result = cloneData.filter(parent => {
      // 返回每一项的子级数组
        const branchArr = cloneData.filter(child => parent.id === child.parent_id)

        // 若子级存在,则给子级排序;且,赋值给父级
        if (branchArr.length > 0) {
          branchArr.sort(this.compare('order'))
          parent.children = branchArr
        }
        // 返回最高的父级,即,parent_id为0,
        return parent.parent_id === 0
      })
      // 给最高级的父级排序
      result.sort(this.compare('order'))
      return result
    },
    // 对象数组排序
    compare(property) {
      return function(a, b) {
        const value1 = a[property]
        const value2 = b[property]
        return value1 - value2// 升序,降序为value2 - value1
      }
    },
  }
  • 效果
[
  { 'id': 6, 'title': '首页', 'leave': 1, 'order': 1, 'parent_id': 0, 'url': '/home' },
  { 'id': 1, 'title': '物业管理', 'leave': 1, 'order': 1, 'parent_id': 0, 'url': '/estate1',
    children:[
      { 'id': 2, 'title': '费用管理', 'leave': 2, 'order': 1, 'parent_id': 1, 'url': 'estate',
        children:[
          { 'id': 3, 'title': '临时收费', 'leave': 3, 'order': 1, 'parent_id': 2, 'url': 'charge' },
          { 'id': 4, 'title': '物业费', 'leave': 3, 'order': 2, 'parent_id': 2, 'url': 'propertyFees' },
        ]
      }
    ]
   },
  { 'id': 5, 'title': '关于', 'leave': 1, 'order': 1, 'parent_id': 0, 'url': '/about' }
]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Node.js 中的图片处理模块有很多,以下是一些常用的: 1. Sharp:一个高性能的图片处理库,支持缩放、裁剪、旋转、锐化、模糊等操作。 2. Jimp:一个纯 JavaScript 编写的图片处理库,支持常见的图片操作,如缩放、裁剪、旋转、滤镜等。 3. GraphicsMagick:一个功能强大的图片处理库,支持多种格式的图片处理,如缩放、旋转、剪裁等,可以通过 Node.js 的 gm 模块调用。 4. ImageMagick:与 GraphicsMagick 类似,同样是一个功能强大的图片处理库,也可以通过 Node.js 的 imagemagick 模块调用。 5. canvas:一个基于 HTML5 Canvas 的图片处理库,支持绘制、裁剪、变换等操作,可以在 Node.js 中使用。 以上是一些常用的 Node.js 图片处理模块,你可以根据自己的需求选择合适的模块。 ### 回答2: Node.js中有一些常用的图片处理模块,可以方便地进行图片的处理和操作。 1. GraphicsMagick:它是一个强大的开源图片处理库,Node.js使用gm模块来对其进行封装。它支持各种图片格式的读取与写入,可以进行图片缩放、裁剪、旋转、合并等操作。使用该模块可以很方便地在Node.js处理大量的图片。 2. Sharp:这是一个高性能的图像处理库,可以用于修改、调整和转换图像。它支持图片的压缩、缩放、裁剪、旋转等操作,并具有较高的速度和内存使用效率。Sharp在处理大型图片时表现出色,是一个非常流行的图片处理模块之一。 3. Jimp:这是一个纯JavaScript编写的图片处理库,可以在Node.js中进行图片的处理和操作。它支持常见的图片格式,并且提供了丰富的API来进行图片的缩放、裁剪、颜色处理、文本叠加等操作。Jimp易于学习和使用,适合用于简单的图片处理需求。 这些图片处理模块都可以在Node.js中很方便地安装和使用,可以根据具体的需求选择适合自己的模块来处理图片。无论是对于网站的图片上传和处理,还是对于图像数据的分析和处理,Node.js的图片处理模块都能提供便捷的解决方案。 ### 回答3: Node.js中的图片处理模块有很多选择,其中一些最受欢迎和广泛使用的模块包括: 1. `sharp`:这是一个高性能的图像处理库,可以在Node.js快速处理图像。它支持图像的调整大小、裁剪、旋转、转换格式、应用滤镜等操作。 2. `gm`:这是另一个流行的图像处理模块,可以使用GraphicsMagick或ImageMagick在Node.js中进行图像操作。它支持图像的剪裁、缩放、旋转、转换格式等功能。 3. `jimp`:这是一个纯JavaScript编写的图像处理库,在Node.js中可以进行图像的调整大小、裁剪、旋转、滤镜应用等操作。它提供了易于使用的API,并且支持跨平台使用。 4. `lwip`:这是一个轻量级的图像处理库,可以在Node.js中进行图像的缩放、裁剪、旋转等操作。它提供了简单的API和异步操作,适合用于快速的图像处理需求。 除了以上提到的模块,还有许多其他的图像处理模块可供选择,每个模块都有其特定的优点和适用场景。根据项目需求和个人偏好,选择合适的模块进行图像处理是非常重要的。需要根据具体的使用情况和需求来评估各个模块的性能、功能和易用性,并选择最适合的模块来完成工作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值