如何在 JavaScript 中转换字符串类型值到数组类型值?
要转换字符串类型值到数组类型值,请使用 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' } ]
广告