如何在 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' }
]

更新於: 2020-9-10

327 瀏覽量

開啟您的 職業生涯

完成課程並獲得認證

開始
廣告