Overwriting arguments object for a Javascript function

痴心易碎 提交于 2019-12-11 16:58:42

问题


If I have the following:

    // Clean input.
    $.each(arguments, function(index, value) {

        arguments[index] = value.replace(/[\W\s]+/g, '').toLowerCase();
    });

Would that be a bad thing to do? I have no further use for the uncleaned arguments in the function, and it would be nice not to create a useless copy of arguments just to use them, but are there any negative effects to doing this?

Ideally I would have done this, but I'm guessing this runs into problems since arguments isn't really an Array:

    arguments = $.map(arguments, function(value) {

        return value.replace(/[\W\s]+/g, '').toLowerCase();
    });

Thanks for any input.

EDIT: I've just realized that both of these are now inside their own functions, so the arguments object has changed. Any way to do this without creating an unnecessary variable?


回答1:


I would not have thought that arguments[i] = value; works, because of the same reason (it is not a real array).

You really should consider to assign the cleaned values to a new variable:

var cleaned_args = $.map(arguments, function(value) {
    return value.replace(/[\W\s]+/g, '').toLowerCase();
});

Introducing a new variable here is not unnecessary. Most often you don't directly operate on arguments anyway (because of its shortcomings like the one you already discovered), but convert it to a real array first (which will involve a new variable anyway).

Regarding your edit:

Right, the first one would not work because arguments refers to the arguments of the anonymous function.



来源:https://stackoverflow.com/questions/5000758/overwriting-arguments-object-for-a-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!