Jquery / Javascript删除双引号表单数组值

时间:2015-09-29 06:24:49

标签: javascript jquery arrays escaping

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

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

1 个答案:

答案 0 :(得分:2)

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

  

eval()方法评估表示为字符串的JavaScript代码。



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