js中数组的number或string类型转换 及其他api

2 篇文章 0 订阅

将String类型的数组转为Number类型:a.map(Number)

 

将Number类型的数组转为String类型:a.map(String)

      let a = ['1', '2', '3'];

      let b = [4, 5, 6];
      
      console.log(a.map(Number))

      console.log(b.map(String))

打印结果: 

替换字符串中指定字符: a.replace(/指定字符/,'替换后的字符')

      var str = "Visit Microsoft!"

      let key = str.replace(/Visit/, "My");
      console.log(key)

      //输出:My Microsoft!

求数组中的最大值:Math.max([...arr])

求数组中的最小值:Math.min([...arr])

      let num = [1,9,2,5,20,4]

      let max = Math.max(...num)
      let min = Math.min(...num)
      
      console.log(max)//输出:20

      console.log(min)//输出:1

对两数组对象的指定值进行过滤:filter()

//删除两数组对象中相同id的对象
    
let a = [
      { id: 1, name: 'aa' },
      { id: 2, name: 'bb' },
      { id: 3, name: 'cc' }
    ]

    let b = [
      { id: 1, name: 'dd' },
      { id: 2, name: 'ff' },
    ]

    //删除a数组对象中跟b相同id的对象
    let ary = a.filter(item => !b.some(ele => ele.id === item.id));
    console.log(ary)
    //输出   [{ id: 3, name: 'cc' }]

筛选两个数组间id相同的数对象:

    let a = [
      { id: 1, name: 'aa' },
      { id: 2, name: 'bb' },
      { id: 3, name: 'cc' }
    ]

    let b = [1, 2]

    // 保留a数组中id跟b相同的对象
    let ary = a.filter(t => b.includes(t.id))

    console.log(ary)
    // 输出   [{ id: 1, name: 'aa' },{ id: 2, name: 'bb' }]

删除对象中的指定属性 ↓

// 例如需要得到一个新对象,里面删除num、descript两个属性↓

let ary = {
      id: 1,
      name: 'aa',
      num: 44,
      descript: '测试测试',
      create_time: '2022-06-15 15:17:30'
    }

    const { num, descript, ...rest } = ary

    console.log(rest)
    // 输出:{id: 1, name: 'aa', create_time: '2022-06-15 15:17:30'}

生成长度为10,数字为0-9的数组:Array.from()

    let arr = Array.from({ length: 10 }).map((t, i) => {
      return i;
    });
    console.log(arr);
    //输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

caicaicai404

对作者使用钞能力,欢迎点这里

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值