前端 数据的转换
JSON 与 Javascript 中对象变量的转换
JSON字符串 ==> js对象-----------------------JSON.parse()
js对象 ==> JSON字符串-----------------------JSON.stringfy()
在JavaScript中,有多种方法可以进行数据类型转换。下面是一些常用的数据类型转换方法的详细介绍和示例:
转换为字符串:
-
使用
String()
函数将其他数据类型转换为字符串:
String(123); // "123"
String(true); // "true"
- 使用
toString()
方法将数字类型转换为字符串:
(123).toString(); // "123"
示例
let num = 456;
let strNum = String(num); // 转换为字符串
console.log(typeof strNum); // "string"const arr = [1,2,3,4,5,6,7]
console.log(arr.toString()); // 1,2,3,4,5,6,7
转换为数字:
- 使用
Number()
函数将其他数据类型转换为数字:
Number("123"); // 123
Number("hello"); // NaN(非数字)
- 使用
parseInt()
或parseFloat()
函数将字符串转换为整数或浮点数:
parseInt("123"); // 123
parseFloat("3.14"); // 3.14
示例
let strNum = "789";
let num = Number(strNum); // 转换为数字
console.log(typeof num); // "number"// 只取整数
const arr = [111.1,55]
console.log(parseInt(arr)); //111
转换为布尔值:
- 使用
Boolean()
函数将其他数据类型转换为布尔值:
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true
示例
let str = "hello";
let bool = Boolean(str); // 转换为布尔值
console.log(typeof bool); // "boolean"
转换为数组:
- 使用
Array.from()
方法将类数组对象或可迭代对象转换为数组:
Array.from("hello"); // ["h", "e", "l", "l", "o"]
Array.from(document.querySelectorAll("li")); // [li, li, li]
- 使用
Array.isArray()
方法判断一个对象是否为数组:
Array.isArray([1, 2, 3]); // true
示例
let str = "hello";
let arr = Array.from(str); // 转换为数组
console.log(Array.isArray(arr)); // trueconst arr = [111.1,55]
console.log(Array.isArray(arr)); //true
转换为对象:
- 使用
Object()
函数将其他数据类型转换为对象:
Object(123); // Number {123}
Object("hello"); // String {"hello"}
- 使用
JSON.parse()
方法将 JSON 字符串转换为对象:
let json = '{"name":"John", "age":30}';
let obj = JSON.parse(json);
示例
let str = "hello";
let obj = Object(str); // 转换为对象
console.log(typeof obj); // "object"let json = '{"name":"John", "age":30}';
let obj = JSON.parse(json);
参考:
cccJSON详解及JSON数据的转换_json数据 中的 = 转换:-CSDN博客
前端常用数据类型转换方法总结_前端数据类型转换-CSDN博客