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")
保留几位小数 (四舍五入 & 非四舍五入)
var num =2.446242342;
num = num.toFixed(2); // 输出结果为 2.45
- 先把小