I don't understand why JSON.parse('[123]')
returns an integer 123
? Shouldn't it return an array [123]
?
Here is the fiddle .
How can I get an array of a single integer after JSON.parse()
?
It is an array, only when it is printed, the brackets are not printed.
Take a look at this one with two items: http://jsfiddle.net/2z355/4/
It prints as 123,456
, also without brackets.
el.innerHTML = JSON.parse('[123]'); // The one item: 123
el.innerHTML = JSON.parse('[123]')[0]; // First item of array: 123
el.innerHTML = JSON.parse('[123,456]') // Both values: 123,456;
el.innerHTML = JSON.parse('[123,456]')[0] // First item: 123;
And also
el.innerHTML = typeof JSON.parse('123'); // number
el.innerHTML = typeof JSON.parse('[123]'); // object *)
I'd have expected 'array' there, but it turns out to be an object. Maybe I've been PHPing too much lately. Nevertheless, it's not a number. :) Fortunately the next line will work (thanks to icktoofay).
el.innerHTML = JSON.parse('[123]') instanceof Array; // true
It is an array of a single integer; it's just that a quirk of JavaScript makes the string representation of an array be the string representations of the elements joined by commas, without the [
and ]
.
You know it's an array because
result instanceof Array
JSON.stringify(result) === '[123]'
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.