简体   繁体   中英

converting a string into a js array

I am probably doing a very small and fundamental mistake here. I am getting some information in the dom which exactly looks like this

<span id="pids" style="display:none">["26551826","22956811","22959266"]</span>

Which then I am trying to convert into a js array. For that I am doing this

var x = document.getElementById('pids');
var y = eval(x);

alert(y.length);

And the result is undefined. What am I doing wrong here?

Here is my fiddle

http://jsfiddle.net/sghoush1/sbrmT/2/

Try this : http://jsfiddle.net/sbrmT/3/

var x = document.getElementById('pids').innerText; //you need to get the value
var y = JSON.parse(x); //dont use eval , json.parse will do.

alert(y.length);

尝试这个 -

var x = document.getElementById('pids').innerHTML;

http://jsfiddle.net/8vS2D/

var x = document.getElementById('pids');
var y = eval(x);

alert(eval(x.innerText));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM