覆盖 Javascript 函数的参数对象
如果我有以下情况:
// Clean input.
$.each(arguments, function(index, value) {
arguments[index] = value.replace(/[\W\s]+/g, '').toLowerCase();
});
那是一件坏事吗?我不再使用函数中未清理的参数,最好不要只是为了使用它们而创建无用的参数副本,但这样做会产生任何负面影响吗?
理想情况下我会这样做,但我猜这会遇到问题,因为 arguments
并不是真正的数组:
arguments = $.map(arguments, function(value) {
return value.replace(/[\W\s]+/g, '').toLowerCase();
});
感谢您的任何输入。
编辑:我刚刚意识到这两个现在都在它们自己的函数内,因此参数对象已经更改。有什么方法可以在不创建不必要的变量的情况下做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于同样的原因(它不是真正的数组),我不会认为
arguments[i] = value;
有效。您确实应该考虑将清理后的值分配给新变量:
在这里引入新变量并不是不必要的。大多数情况下,您无论如何都不会直接对参数进行操作(因为它的缺点就像您已经发现的那样),而是首先将其转换为真正的数组(无论如何,这都会涉及一个新变量)。
关于您的编辑:
是的,第一个不起作用,因为
arguments
引用了匿名函数的参数。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:
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.