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

javascript - Why JSON.parse('[123]') returns 123? - Stack Overflow

programmeradmin2浏览0评论

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()?

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()?

Share Improve this question asked Jul 19, 2013 at 5:50 esengineeresengineer 9,9387 gold badges51 silver badges69 bronze badges 2
  • 6 Array.isArray(JSON.parse('[123]')) === true. – beatgammit Commented Jul 19, 2013 at 5:54
  • >> JSON.parse('[123]') // [123] - what r u talkin bout ? and it is ==123 and not ===123. js just tries to extract numbers – Royi Namir Commented Jul 19, 2013 at 6:15
Add a ment  | 

2 Answers 2

Reset to default 10

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/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 mas, without the [ and ].

You know it's an array because

  1. result instanceof Array
  2. JSON.stringify(result) === '[123]'
发布评论

评论列表(0)

  1. 暂无评论