[英]Checking for presence of array in parameters
我目前正在檢查傳遞給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.
您可以使用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>
看到再次更新的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
它的作用是為您提供一個實用程序函數來檢查傳遞給yourFunction
的arguments
對象是否在任何地方包含一個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
唯一的參數是數組,或者參數都不是數組:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.