[英]How to convert a string that formatted as array variable into javascript object?
[英]How to convert string [formatted in array] into array javascript
我正在使用nodejs處理Api,我想將字符串格式[10,20]轉換為數組。
例如
//我的同事送我字符串
employee_id : [ 10, 20 ];
我檢查一下
if(Array.isArray(employee_id) || employee_id instanceof Array){
}
它不起作用
我嘗試輸入typeof employee_id; it's return string
typeof employee_id; it's return string
如何將格式字符串更改為數組
在比較之前將結果解析為JSON。
const employees = JSON.parse(employee_id)
if(Array.isArray(employees) {
}
它可能對你有幫助。
您可以嘗試使用JSON.parse()
:
JSON.parse()
方法解析JSON字符串,構造字符串描述的JavaScript值或對象。
if(Array.isArray(JSON.parse(employee_id)) || JSON.parse(employee_id) instanceof Array){
}
演示:
var obj = {employee_id : '[ 10, 20 ]'}; console.log(typeof obj.employee_id);//string if(Array.isArray(JSON.parse(obj.employee_id)) || JSON.parse(employee_id) instanceof Array){ console.log('array') }
API返回JSON字符串,因此您必須將字符串解析為JSON對象以檢查實際數據類型。
if(Array.isArray(JSON.parse(employee_id)) || JSON.parse(employee_id) instanceof Array){
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.