渡されたいくつかの配列引数をループする方法を理解しようとしています。例:[1,2,3,4,5]、[3,4,5]、[5,6,7]関数に渡す場合、各引数内に関数ループをどのように設定しますか(任意渡すことができる配列の数)?
ここではforループを使用したいと思います。
渡されたいくつかの配列引数をループする方法を理解しようとしています。例:[1,2,3,4,5]、[3,4,5]、[5,6,7]関数に渡す場合、各引数内に関数ループをどのように設定しますか(任意渡すことができる配列の数)?
ここではforループを使用したいと思います。
これには引数を使用できます。
for(var arg = 0; arg < arguments.length; ++ arg)
{
var arr = arguments[arg];
for(var i = 0; i < arr.length; ++ i)
{
var element = arr[i];
/* ... */
}
}
以下のように、forEachを使用します。
'use strict';
function doSomething(p1, p2) {
var args = Array.prototype.slice.call(arguments);
args.forEach(function(element) {
console.log(element);
}, this);
}
doSomething(1);
doSomething(1, 2);
使用している配列の数を含む組み込みのarguments
キーワードを使用します。length
これをベースとして、各アレイをループします。
function loopThroughArguments(){
// It is always good to declare things at the top of a function,
// to quicken the lookup!
var i = 0,
len = arguments.length;
// Notice that the for statement is missing the initialization.
// The initialization is already defined,
// so no need to keep defining for each iteration.
for( ; i < len; i += 1 ){
// now you can perform operations on each argument,
// including checking for the arguments type,
// and even loop through arguments[i] if it's an array!
// In this particular case, each argument is logged in the console.
console.log( arguments[i] );
}
};