Javascript foreach syntax

Source: Internet
Author: User

First, although it is called the foreach syntax, the keyword is still for. This syntax is just a simplification of the for syntax that is usually used.

 

This syntax is usually used to traverse arrays at most. At this time, each loop obtains an array index (an integer), and then obtains the objects in the array through the array name [integer Index.

 

However, this syntax can also be used to traverse objects and get the object's attribute name (a string). Then, you can get the object through the object name [attribute name.

 

Therefore, the key to understanding the syntax is to understand what each loop gets.

In fact, the implementation of this function is benefited from the fact that the array index of javascript can be a string. If you cannot (think about Java), you will not be able to sing this story.

< Html >
< Heap >
< Script Type = "Text/JavaScript" >
VaR Mycolors =   New Array ( ' Blue ' , ' Red ' , ' Yellow ' );
Function F1 (){
VaR Content = "" ;
For ( VaR Key In Mycolors ){
Content + = Key + " : " + Mycolors [Key] + " <Br/> " ;
}
Document. getelementbyid ( " Content " ). Innerhtml = Content;
}

Function User (){}

Function F2 (){
VaR U1 = New User ();
U1.uname = " Zhang San " ;
U1.age = " 18 " ;

VaR Content = "" ;
For ( VaR Key In U1 ){
Content + = Key + " : " + U1 [Key] + " <Br/> " ;
}
Document. getelementbyid ( " Content " ). Innerhtml = Content;
}
</ Script >
</ Heap >
< Body >
< Input Type = "Button" ID = "C1" Name = "C1" Onclick = "F1 ();" Value = "Click one" />
< Input Type = "Button" ID = "C2" Name = "C2" Onclick = "F2 ();" Value = "Click two" />
< Div ID = "Content" > </ Div >
</ Body >
</ Html >

Click click one and output:

0: Blue
1: red
2: Yellow

 

Click click two and output:

Uname: James
Age: 18

Of course, if U1 has a method:

U1.sai = function (){
Alert ("hello ");
}

Click click two and the output will be:

Uname: James
Age: 18
SAI: function () {alert ("hello ");}

Now you should know how to traverse a JSON object !! 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.