Jquery/Javascript 从数组值中删除双引号

Jquery/Javascript remove double quotes form array value

myArray = ["{url: '/delete', key: 71}", "{url: '/delete', key: 72}", "{url: '/delete', key: 73}", "{url: '/delete', key: 74}"]

我想删除包装对象的 " 字符。或者从双引号中转义。

我试过了

myArray.replace(/"/g,"")

但上面写着:

Uncaught TypeError: myArray.replace is not a function

有人有同样的经历吗?谢谢

您可以使用map() and eval()将字符串数组转换为对象数组

The eval() method evaluates JavaScript code represented as a string.

var myArray = ["{url: '/delete', key: 71}", "{url: '/delete', key: 72}", "{url: '/delete', key: 73}", "{url: '/delete', key: 74}"];

myArray = myArray.map(function(v) {
  return eval('(' + v + ')');
});

document.write(JSON.stringify(myArray));

这不是一个好方法,您可以使用有效的 json 格式发送数据。这将比上述方法安全得多。例如: ["{\"url\": \"/delete\", \"key\": 71}", "{\"url\": \"/delete\", \"key\": 72}", "{\"url": \"/delete\", \"key\": 73}", "{\"url\": \"/delete\", \"key\": 74}"],在这种情况下,您可以使用 JSON.parse() 而不是 eval()

在ruby中可以将数组转换为JSON字符串,参考Ruby: How can I convert an array of data to hash and to json format? , Parsing a Ruby Array to JSON