javascript“for (x in y)”语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7873673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:36:29  来源:igfitidea点击:

javascript "for (x in y)" statements

javascriptfor-loopfor-in-loop

提问by SiriusKoder

//just copied this code from w3schools
var person={fname:"John",lname:"Doe",age:25}; 

for (x in person)
{
document.write(person[x] + " ");
}

I want to know that, what I have to assume instead of "x".

我想知道,我必须假设而不是“x”。

采纳答案by Sarfraz

The personis object and Xis variable used in iteration of the forloop, you can name it anything other than Xalso :). Here Xworks as keyof the object for example:

person是对象,X是在迭代变量使用的for循环,你能说出它比其他任何东西X也:)。这里X可以作为key例如对象:

alert(person["fname"]);

Here fnameis stored in Xalong with other keys such as lnameand age.

Here与其他键一起fname存储,X例如lnameage

回答by Duncan MacLeod

You want to have

你想拥有

for ( x in Object.keys(person)) {
  console.log(person[x]);
}

this will give you a list of KEYS rather than a list of values.

这将为您提供一个键列表而不是值列表。