-1

I need to allow only vectors like function([a, b, c, d]) or function(a, b, c, d) to my program. I need to write a unit test that gives a syntax error when I get parameters of the form function([a, b][c, d]) and function([a][b][c][d]).

Note that I am not looking for just an array here. I need to filter out multiple arrays and only take in single dimensional array (or no arrays at all)

How can I check the existence of such parameters?

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Kunal Vyas
  • 1,499
  • 1
  • 23
  • 40
  • 2
    possible duplicate of [How do you check if a variable is an array in JavaScript?](http://stackoverflow.com/questions/767486/how-do-you-check-if-a-variable-is-an-array-in-javascript) – Bik Jun 22 '15 at 05:58
  • @Bik This is not a duplicate of the question you have referenced. In addition to it being an array, I need to check if its multidimensional. – Kunal Vyas Jun 22 '15 at 06:17
  • None of your examples features an array of arrays. Note: There are no multidimensional arrays in JS, only arrays of arrays. – Felix Kling Jun 22 '15 at 06:19
  • 1
    How exactly does this differ from your [previous question](http://stackoverflow.com/questions/30970398/checking-for-presence-of-array-in-parameters)? – Felix Kling Jun 22 '15 at 06:22
  • In my previous question, I was looking for ([a], [b]) whereas, now I need to write a specific unit test case for an input of the type ([a][b]). The former is a valid input whereas the latter isn't. I want to throw a more specific error to the user of the function. – Kunal Vyas Jun 22 '15 at 06:27

3 Answers3

0

If your function always takes one or more arguments, You can check by testing Array.isArray(arguments[i]) .

turutosiya
  • 1,051
  • 10
  • 17
0
function myMethod(param){
    if(param instanceof Array)
    {
        // check that no element is an array
        return !param.some(function(item){
            return item instanceof Array;
        });
    }

    return false;
}

console.log(myMethod([1,2,3,4])); // true
console.log(myMethod([1,2,3,4, [1,2]])); // false

I don't really understand how you have an input that can be a,b,c,d and [a,b,c,d] - What is your prototype?

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
-1

you can always check its children if it is array or not

x = [[1,2,3], [4,5,6]];
if(Array.isArray(x))//true since x is a array
    if(Array.isArray(x[0])) //true since x[0] is array
        console.log('x is two dimensional array')
Strikers
  • 4,698
  • 2
  • 28
  • 58
  • @downvoter can you please explain the reason for downvote – Strikers Jun 22 '15 at 06:03
  • Though I did not downvote your answer, but I'm not sure if this is what I'm looking for. Instead of `x = [[1,2,3], [4,5,6]];`, I'm looking for detection of the type `x = [[1,2,3][4,5,6]];` (without the comma) – Kunal Vyas Jun 22 '15 at 06:42
  • 1
    x = [[1,2,3][4,5,6]]; is not valid in javascript except if it is a string – Strikers Jun 22 '15 at 12:52