javascript - Rhino 不枚举 'arguments' 到一个函数

标签 javascript linux rhino jvm-arguments enumerate

我正在尝试使用函数可用的“arguments”变量来枚举传递给函数的参数,在 Javascript 中,使用:

for (var i in arguments){
   ...
}

这似乎适用于 chrome 和 firebug 控制台,但不适用于 Rhino。对于前两者,我可以成功进入 for 循环并查看参数,而对于后者,似乎甚至没有进入 for 循环。

为什么会发生这种情况,我该如何预防?

最佳答案

来自 Javascript for..in looping over arguments ie.for( arg in arguments) does not work in IE8 but it works in Chrome 8 :

First of all, while the arguments object available within a function is not an array, it is "array-like" enough such that an incremental for loop (for (var i = 0, len = arguments.length; i < len; i++) { ... }) is preferable - not only because it runs faster, but also because it avoids other pitfalls - one of which is exactly what you're falling into.

To actually answer the question of why the second loop doesn't work, it's important to realize just what for ... in loop does: it iterates through all enumerable properties found in an object. Now, I've bolded 2 words in that statement, because I used these two words purposefully to indicate a couple of nuances that, while they may seem subtle, can drastically affect the behavior of your code if you don't realize what's going on.

First let's focus on all - by which I mean to say, not just properties of the object itself, but also potentially properties said object has inherited from its prototype, or its prototype's prototype, or so on. For this reason, it is very often recommended that you "guard" any for ... in loop by immediately additionally qualifying it with the condition if (obj.hasOwnProperty(p)) (assuming your loop were written for (var p in obj)).

But that's not what you're running into here. For that, let's focus on that second word, enumerable. All properties of objects in JavaScript are either enumerable or non-enumerable, which pretty much directly relates to whether the property shows up in a for ... in loop or not. In browsers such as Firefox and IE, as it turns out, the arguments object's numeric properties are not enumerable (nor is its length as it were), which is precisely why you're not iterating through anything!

关于javascript - Rhino 不枚举 'arguments' 到一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7006285/

相关文章:

C Pthread : Kill other threads gracefully through one thread

java - 从 Rhino 返回多个值到 Java 调用类

java - 在字符串上调用替换会抛出 EvaluatorException

javascript - 为什么这个setTimeout();功能不能像我想象的那样工作?

javascript - 为什么这些值彼此不相等?

linux - 并行make : set -j8 as the default option

javascript - 使用 RHINO js 引擎发起 http 请求

javascript - 按下时打印键的名称?

javascript - Javascript 无法正确读取 ASCII > 128 的字符

linux - 在 Debian Wheezy 上使用 SASL 构建 libmemcached