我对 JavaScript 的要求之一是,我试图将从数据库传递的字符串转换为 JavaScript 对象。
第一步: 从数据库传递的字符串:
"validator":["required","numeric","maxLength:14","{type: amountValidate}"]
Step2:使用JSON.Parse()方法转换为javascript对象,输出如下:
validator: Array(4)
0: "required"
1: "numeric"
2: "maxLength:14"
3: "{type: amountValidate}"
length: 4
预期输出为: 在下面的代码中,amountValidate 通过 tabulator js api 转换为函数。
validator:["required","numeric","maxLength:14",{
type:amountValidate,
}]
由于我将以下函数应用于 type:amountValidate,因此它应该表现为变量,并且不应包含在双引号中。
var amountValidate = function(cell, value, parameters){
var regex = /^\s*-?(\d+(\.\d{1,2})?|\.\d{1,2})\s*$/
var n = value.match(regex);
if(n !== null){
return true;
}else{
return false;
}
}
提前致谢。
最佳答案
这里的主要问题是您的字符串不是有效的 JSON。应该是这样的:
'{"validator": ["required","numeric","maxLength:14", {"type": "amountValidate"}]}'
在线有多个 json 格式化程序/验证程序,例如 this one ,您可以用它来检查它。
关于javascript - 在javascript中无法将字符串转换为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58420573/