美文网首页
这些JS常用的解析函数别再傻傻分不清了

这些JS常用的解析函数别再傻傻分不清了

作者: 似朝朝我心 | 来源:发表于2021-06-23 20:04 被阅读0次

JSON.parse()方法:将一个有效的JSON字符串解析成JS对象

JSON 通常用于与服务端交换数据。
在接收服务器数据时一般是字符串。

我们可以使用 JSON.parse() 方法将数据转换为 JavaScript 对象。

const str ='{"user":"Tom","age":21}'
console.log(JSON.parse(str))

输出:{ user: 'Tom', age: 21 }

JSON.stringify()方法:把 JavaScript 对象转换为JSON字符串。

JSON 的常规用途是同 web 服务器进行数据交换。
在向 web 服务器发送数据时,数据必须是字符串。

const obj = {
    name: 'Tom',
    age: 21,
    gender: '男'
}
const newObj = JSON.stringify(obj)
console.log(newObj);
console.log(typeof newObj);

输出:
{"name":"Tom","age":21,"gender":"男"}
string

toString() 方法可把一个 Number 对象转换为一个字符串,并返回结果。

const numObj = new Number(123456)
console.log(`数据类型是:${typeof numObj},输出结果为:${numObj}`);
const str = numObj.toString()
console.log(`现在数据类型是:${typeof str},输出结果为:${str}`);

输出:
数据类型是:object,输出结果为:123456
现在数据类型是:string,输出结果为:123456

node中,最常用的就是处理二进制buffer数据,进制转换。

const buf = Buffer.from('run');
console.log(buf);
console.log(typeof buf);
console.log(buf.toString());

输出:
<Buffer 72 75 6e 6f 6f 62>
object
run

parseInt() 函数可解析一个字符串,并返回一个整数。

const str = '12345'
const num = parseInt(str)
console.log(typeof str);
console.log(num);
console.log(typeof num);

输出:
string
12345
number

parseFloat() 函数可解析一个字符串,并返回一个浮点数。

const str = '12.133'
const float = parseFloat(str)
console.log(float);
console.log(typeof float);

输出:
12.133
number

toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。

const float = 12.64894
console.log(float.toFixed(3));

输出:
12.649

parse() 方法:返回 1970/01/01 至 xxxx/xx/xx 之间的毫秒数(时间戳):

//算出 1970/01/01 至 2021/06/23 之间的毫秒数
var d = Date.parse("05 23, 2021"); //2021-06-23
console.log(d);

输出:
1613836800000

相关文章

网友评论

      本文标题:这些JS常用的解析函数别再傻傻分不清了

      本文链接:https://www.haomeiwen.com/subject/frgvyltx.html