最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - convert an input value in array - Stack Overflow

programmeradmin2浏览0评论

I have this data in an input: [16,57.35], [23,56.26], [34,54.57]

and I want to turn it into an array

var data =$('#data').val();
var array = JSON.parse ("["+data+"]");

I'm having this error

Uncaught SyntaxError: Unexpected token.

How I can fix it or I can convert the input value in array?

I have this data in an input: [16,57.35], [23,56.26], [34,54.57]

and I want to turn it into an array

var data =$('#data').val();
var array = JSON.parse ("["+data+"]");

I'm having this error

Uncaught SyntaxError: Unexpected token.

How I can fix it or I can convert the input value in array?

Share Improve this question edited Jul 9, 2013 at 17:05 user229044 240k41 gold badges344 silver badges347 bronze badges asked Jul 9, 2013 at 16:57 MarztresMarztres 4709 silver badges15 bronze badges 3
  • 5 Works here... – Teemu Commented Jul 9, 2013 at 17:02
  • 2 Please do a console.log(data) and post here what you are actually passing in. – Bergi Commented Jul 9, 2013 at 17:13
  • 1 Also check data.length, maybe there are some non-printing characters in it. – Teemu Commented Jul 9, 2013 at 17:14
Add a ment  | 

2 Answers 2

Reset to default 4

Your code is working check it here, you may need to include required jQuery library or check some thing else in the code causing it.

data = $('#txt1').val();
arr = JSON.parse ("["+data+"]");
console.log(arr);

Try using the eval function:

var data = "123, 456, 789";
var array = eval("[" + data + "]");

You'll need to make sure that whatever you're inputting is valid JSON, but the above code will output an array for you. Hope it helps.

发布评论

评论列表(0)

  1. 暂无评论