最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

for loop - javascript "for (x in y)" statements - Stack Overflow

programmeradmin4浏览0评论
//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".

//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".

Share Improve this question edited Jan 5, 2016 at 11:46 Lucky 17.4k19 gold badges120 silver badges156 bronze badges asked Oct 24, 2011 at 9:39 SiriusKoderSiriusKoder 3412 gold badges4 silver badges12 bronze badges 6
  • Can you specify a little more? What are you trying to achieve? – Jørgen Commented Oct 24, 2011 at 9:43
  • Make sure you declare x first... – Matt Commented Oct 24, 2011 at 9:44
  • 3 for a better reference look here: developer.mozilla/en/JavaScript/Reference/Statements/… and why so, look here: w3fools. – Yoshi Commented Oct 24, 2011 at 9:45
  • Avoid using for in. Use for(var i=0;i<person.length;i++) instead. – OptimusCrime Commented Oct 24, 2011 at 10:24
  • 1 Could you explain why? @OptimusCrime – Alexander Mistakidis Commented Dec 11, 2012 at 15:53
 |  Show 1 more ment

2 Answers 2

Reset to default 6

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.

The person is object and X is variable used in iteration of the for loop, you can name it anything other than X also :). Here X works as key of the object for example:

alert(person["fname"]);

Here fname is stored in X along with other keys such as lname and age.

发布评论

评论列表(0)

  1. 暂无评论