JavaScript:对于...每个/与

标签 javascript

<分区>

Possible Duplicate:
JavaScript foreach Vs for

for 循环和 for...in 有什么区别?我的意思是,即使有差异,也不会太大。

而且,我有时会在验证脚本中看到函数编写如下:

function check() {
    with(something) {
        if(){
            // do something
        }
    }
}

“with”条件有什么意义?

最佳答案

for each..in语句在对象属性的所有值上迭代指定变量。对于每个不同的属性,执行指定的语句。这是 Mozilla 在 JavaScript 1.6 中引入的(参见下面 @CMS 的评论),并非所有主流浏览器都支持。

对于每个例子:

var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for each (var item in obj) {
  sum += item;
}
console.log(sum); // prints "26", which is 5 + 13 + 8

类似的说法是for..in ,它迭代属性名称而不是属性值。使用 for..in 编写的相同示例:

var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for (var prop in obj) {
  sum += obj[prop];
}
console.log(sum); // prints "26", which is 5 + 13 + 8

for..in 语句自 JavaScript 1.0 以来就已存在,因此您可以安全地在所有浏览器中使用它。

这些语句不同于传统的for循环,因为它们用于迭代对象的属性。 for 循环可用于迭代数组的元素,但不能用于迭代对象的属性,除非您可以使用 ECMAScript 5 的 Object.keys。 ,可用于实现上述示例,如下所示:

var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
var keys = Object.keys(obj)
for (var i = 0; i < keys.length; i++) {
  sum += obj[keys[i]];
}
console.log(sum); // prints "26", which is 5 + 13 + 8

至于with声明,注意以下几点:

JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a 'ReferenceError' is thrown.

因此,请考虑以下事项:

var prop1 = 10;
var obj = {prop1: 5, prop2: 13, prop3: 8};

with (obj) {
   console.log(prop1); // prints 5 instead of 10
}

不推荐使用 with,ECMAScript 5 中禁止使用 with strict mode .推荐的替代方法是将要访问其属性的对象分配给一个临时变量。

关于JavaScript:对于...每个/与,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4002879/

相关文章:

javascript - Next.js 是否需要运行 Node 服务器?

javascript - 单击 anchor 时如何更改工具提示?

javascript - 扩展 jQuery 插件,无需触及原始插件代码

javascript - 将自动图像 slider 更改为链接点击 slider

javascript - 此功能在 Firefox 中不起作用

javascript - 通过替换 Bootstrap 按钮类来使用图标

javascript - webkit-filter 后获取元素背景色

javascript - D3 v4:具有嵌套g标签的任意复杂数组的元素之间的间距和绑定(bind)

c# - 使用 anchor 指向谷歌地图上的位置

javascript - 通过预处理更改元素 ID 和类