检查参数中是否存在数组

时间:2015-06-21 23:40:26

标签: javascript

我目前正在检查传递给JavaScript函数的参数中的数组。 参数可以是类型:

1. function(a, b, c, d)
2. function([a, b, c, d])
3. function([a], b, c, [d, e, f], g)

我需要检查参数是否包含在单个数组中。以下代码适用于案例1.2.,但不适用于3.

if (Array.isArray(args)){
  // section A
}
else{
  // section B
}

这段代码正在考虑将3.作为一个数组,虽然它有混合值,它正在输入A部分而不是B部分。我希望它输入B部分。只有完全被[]包围的参数应该进入A。

3 个答案:

答案 0 :(得分:1)

您可以使用arguments对象。遍历arguments对象并检查传递的每个参数

test(1, 2, 3, 4);
test([1, 2, 3, 4]);
test([1], 2, 3, [4, 5, 6], 7);

function test() {
  var onlyArray = true;
  for (var i = 0; i < arguments.length; i++) {
    if (!Array.isArray(arguments[i])) {
      onlyArray = false;
      break;
    } 
  }
  if (onlyArray) {
      snippet.log('section A');
      // section A
    } else {
       snippet.log('section B');
      // section B
    }
}
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

答案 1 :(得分:1)

根据您更新的问题

请参阅重新更新的jsfiddle

function containsOneArray(test) {
    return test.length === 1 && Array.isArray(test[0]);
}

function yourFunction() {
    if(containsOneArray(arguments)) {
        console.log(true); 
    } else {
       console.log(false); 
    }
}

yourFunction(['hello']); // true
yourFunction(['i', 'am', 'cool']); // true
yourFunction('hello'); // false
yourFunction(['a'], 'b', 'c', ['d', 'e', 'f'], 'g'); // false

新答案

添加了一些关注点分离(请参阅jsfiddle):

function containsArray(_args) {
    var args = Array.prototype.slice.call(_args),
        contains = false;

    args.forEach(function(arg) {
        if(Array.isArray(arg)) {
            contains = true;
            return; // don't need to keep looping
        }
    });

    return contains;
}

function yourFunction() {
    if(containsArray(arguments)) {
        console.log(true); 
    } else {
       console.log(false); 
    }
}

yourFunction(['hello']); // true
yourFunction('hello'); // false
yourFunction(['a'], 'b', 'c', ['d', 'e', 'f'], 'g'); // true

这样做会为您提供一个实用程序功能,只需检查传递到arguments的{​​{1}}对象是否在任何地方都包含yourFunction

旧答案

查看jsfiddle

Array

答案 2 :(得分:1)

唯一的参数是数组,或者没有参数是数组:

function foo(args)
{
    var v;

    if (arguments.length === 1 && Array.isArray(args)) {
        v = args; // grab vector (B)
    } else if (arguments.length >= 1 && ![].some.call(arguments, Array.isArray)) {
        v = [].slice.call(arguments, 0); (A)
    } else {
        throw "begone, evil caller";
    }
    // do your stuff here
}
相关问题