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

javascript - test if array is multidimensional - Stack Overflow

programmeradmin1浏览0评论

How would I test to see if a variable includes an multidimensional array? For example:

var obj = [1, 2];

vs

var obj = [[1], [2]];

I have used Array.isArray(obj) to test whether is an array, but I can't figure out how to test the number of arrays.

How would I test to see if a variable includes an multidimensional array? For example:

var obj = [1, 2];

vs

var obj = [[1], [2]];

I have used Array.isArray(obj) to test whether is an array, but I can't figure out how to test the number of arrays.

Share Improve this question edited May 23, 2014 at 18:33 user3180105 asked May 23, 2014 at 17:54 user3180105user3180105 3815 silver badges14 bronze badges 6
  • 2 That's easy, open the console and the second one will generate a syntax error ! – adeneo Commented May 23, 2014 at 17:55
  • if( Object.prototype.toString.call( someVar ) === '[object Array]' ) { alert( 'Array!' ); } – tymeJV Commented May 23, 2014 at 17:57
  • 3 A variable can always only contain a single value, hence it can only contain a single array. Maybe you used the wrong words to describe the problem. If so, please provide more context. – Felix Kling Commented May 23, 2014 at 17:59
  • 1 Do u mean multidimensional arrays? – Comfortably Numb Commented May 23, 2014 at 18:00
  • 1 Do you mean var ratings = [[1], [2]]? If so, you'd have to then check if each value is an array as well as checking if ratings is an array. – forgivenson Commented May 23, 2014 at 18:01
 |  Show 1 more ment

1 Answer 1

Reset to default 7

Assuming you meant

var ratings = [[1], [2]];

as var ratings = [1], [2]; is a syntax error, you could do

ratings.filter(Array.isArray).length

to get the number of arrays inside the wrapping array (2)

FIDDLE

发布评论

评论列表(0)

  1. 暂无评论