heyden
heyden

Reputation: 179

why functions return Multidimensional Arrays but the result is a num?

when functions return Multidimensional Arrays(arrays is all num),but the result is a num?

function show(){
    return [1,2][1,2];
}
function show1(){
    return [0,1,2][1,2];
}
function show2(){
    return [0,1,2,3,4,5,6,7,8,9,10,11,12][[0,1,2,[5,9,8,6][2,1,5,0],4,6][1,2,3]];
}
console.log(show());//undefined
console.log(show1());//2
console.log(show2());//5

Upvotes: 4

Views: 93

Answers (2)

Ram
Ram

Reputation: 144709

This is because you are using bracket notation for getting an element from the arrays.

As an example the show1 function returns 2 because:

[0,1,2] defines an array, and [1,2] is a bracket notation for getting an element from the array. The code snippet is equal to: [0,1,2][2], as the comma operator returns the last operand which is 2.

You need to wrap the code snippet with [] for having an array with 2 elements:

[[0,1,2], [1,2]]

Upvotes: 8

Morteza Tourani
Morteza Tourani

Reputation: 3536

The problem is with your syntax. In javascript (and other languages) 2 dimension array is an array of arrays so when you want to declare it in javascript you should do this:

var twoDimArray = [[1, 2], [3, 6]];

Upvotes: 2

Related Questions