Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
like image 276
heyden Avatar asked Dec 24 '22 03:12

heyden


1 Answers

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]]
like image 130
undefined Avatar answered Apr 11 '23 09:04

undefined