鉴于此功能:
function foo( a,b,c ) {
//
}
如何做某事,比如对每个参数使用 console.log() ?我知道您可以使用 Arguments 关键字查看参数。参数似乎返回看起来像数组的内容(但类型为“对象”[惊讶..不是]),但它不支持 .forEach,我正在使用 Chrome。
我尝试将函数修改为此,并期望它能够工作:
function foo( a,b,c ) {
arguments.forEach(function( arg ){
console.log( arg );
});
}
您收到 TypeError: Object # has no method 'forEach' 的错误。
最佳答案
arguments
对象没有 forEach
方法,因此您需要使用 for
循环或for...in
循环。
function foo () {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
foo("Foo", { "bar": 0 }); // Output: Foo, Object {bar: 0}
或者
function foo () {
for (var arg in arguments) {
console.log(arguments[arg]);
}
}
foo("Foo", "Bar"); // Output: Foo, Bar
关于javascript - 如何对 JavaScript 函数中的每个参数执行某些操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13732888/