检查参数中是否存在数组

Checking for presence of array in parameters

本文关键字:存在 数组 是否 参数 检查      更新时间:2023-09-26

我目前正在检查传递给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 中。

要么唯一的参数是数组,要么没有一个参数是数组:

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
}

基于您更新的问题

请参阅再次更新的 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

这样做是为您提供一个实用程序函数,用于检查传递到yourFunctionarguments对象是否包含任何地方的Array

旧答案

看看jsfiddle:

function containsArray() {
    var args = Array.prototype.slice.call(arguments),
        contains = false;
    args.forEach(function(arg) {
        if(Array.isArray(arg)) {
            contains = true;
            return; // don't need to keep looping
        }
    });
    console.log(contains);
    if(contains) {
        // do something   
    } else {
       // do something else   
    }
}
containsArray(['hello']); // true
containsArray('hello'); // false
containsArray(['a'], 'b', 'c', ['d', 'e', 'f'], 'g'); // true

您可以使用参数对象。遍历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>