简体   繁体   English

Javascript 在未定义中“使用严格”

[英]Javascript “use strict” for in undefined

Why in this example:为什么在这个例子中:

for(x in json) {
   //something here
}

is my variable x undefined when if place 'use strict';如果放置'use strict';我的变量x未定义'use strict'; in my script.在我的脚本中。

if i remember correctly, x will be undefined when you collection will something like this: [undefined, undefined] .如果我没记错的话,当您收集时x将是未定义的: [undefined, undefined]

The array is populated but the element is undefined数组已填充但元素undefined

x doesn't appear to be defined in the loop so you need to use x似乎没有在循环中定义,所以你需要使用

for(var x in json) {
   //something here
}

strict mode which is activated by placing 'use strict';通过放置'use strict';来激活strict mode 'use strict'; in a scope, prevents you from using variables that have not been declared in your code.在范围内,防止您使用尚未在代码中声明的变量。 This is done to prevent creating global variables which is the default behavior in browsers on non strict mode.这样做是为了防止创建全局变量,这是非严格模式下浏览器中的默认行为。 so in your case you need to do所以在你的情况下你需要做

for(var x in json) {
  // your code here
}

that way the variable x will be creaed, hoisted and will be ready to be used by the loop in strict mode.这样,变量 x 将被创建、提升并准备好在严格模式下被循环使用。

In strict mode, variables always have to be defined before they are assigned or used.在严格模式下,变量总是必须在分配或使用之前定义。 This means, you have to write这意味着,你必须写

for (var x in json) ...

or或者

var x;
for (x in json) ...

What you're doing is allowed without strict mode, but bad habit, because it automatically declares the variable x in global scope .你正在做的事情没有严格模式是允许的,但这是坏习惯,因为它会自动在全局范围内声明变量x A lot of programmers are doing this wrong, even in some references/tutorials.许多程序员都做错了,即使在一些参考资料/教程中也是如此。

Yes, it will give you an error because, in strict mode, we have to declare variables before actually, we start using them.是的,它会给你一个错误,因为在严格模式下,我们必须在实际开始使用它们之前声明变量。

You can try this.你可以试试这个。

for(var x in json) {
   //something here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM