如何在 JavaScript 中将字符串类型值转换为数组类型?

javascriptweb developmentobject oriented programming更新于 2025/11/14 9:48:17

要将字符串类型值转换为数组类型,请使用 parse() 方法。以下是代码 −

示例

var customerDetails='[
   {"name": "John", "countryName": "US"},
   {"name": "David", "countryName": "AUS"},
   {"name": "Bob", "countryName": "UK"}
]';
console.log("The actual value="+customerDetails);
var convertStringToArray=JSON.parse(customerDetails);
console.log("After converting string to array objects=");
console.log(convertStringToArray);

要运行上述程序,您需要使用以下命令 −

node fileName.js.

输出

此处,我的文件名为 demo123.js。这将产生以下输出 −

PS C:\Users\Amit\JavaScript-code> node demo123.js
The actual value=[{"name": "John", "countryName": "US"}, {"name": "David", "countryName":
"AUS"}, {"name": "Bob", "countryName": "UK"}]
After converting string to array objects=[
   { name: 'John', countryName: 'US' },
   { name: 'David', countryName: 'AUS' },
   { name: 'Bob', countryName: 'UK' }
]

相关文章


有用资源