JavaScript 常用操作(字符串、map、转换)

本文涵盖了JavaScript中的常见操作,包括字符串转换成JSON、数字转换、保留小数位、去空格的方法,Map对象的处理,判断字符串包含特定子串,时间戳与日期之间的转换等实用技巧。
摘要由CSDN通过智能技术生成

JS 字符串相关操作


字符串转json – JSON.stringify( a )

json转字符串 – JSON.parse(a)
        /** 常用例子:发送websocket请求的时候的json */
        const tempSendContent = {
   }
        tempSendContent['id'] = 'uuid'
        tempSendContent['reqType'] = 'sub' // 订阅为 sub ,不订阅为 unsub
        tempSendContent['api'] = 'api/market/v1/test' // 订阅接口类型
        tempSendContent['tempTest1'] = 'test1' // 某某参数 1。。
        tempSendContent['tempTest2'] = 'test2' // 某某参数 2。。
        tempSendContent['frequency'] = 1000 // 数据更新频率
        const sendContent = JSON.stringify(tempSendContent) // object 转 string
        
		const ws = new WebSocket('ws://localhost:9998/test')
		ws.send(sendContent)

		console.log(tempSendContent) // typeof 检测,结果为 object
		// {id: "uuid", reqType: "sub", api: "api/market/v1/test", tempTest1: "test1", tempTest2: "test2", …}
		console.log(sendContent) // typeof 检测,结果为 string
		// {"id":"uuid","reqType":"sub","api":"api/market/v1/test","tempTest1":"test1","tempTest2":"test2","frequency":1000}
		// 输出结果看起来很相似,但 注意 JSON.stringify( object )之后为 string 的 key,是 带双引号 "" 的 ,eg. "id","reqType"

字符串转 数字number

parseFloat

parseFloat("80")

保留几位小数 (四舍五入 & 非四舍五入)

  • 四舍五入 toFixed(3)
var num =2.446242342;
num = num.toFixed(2);  // 输出结果为 2.45
  • 不四舍五入
  1. 先把小
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值