JavaScript trav...LOGIN

JavaScript traverse object properties and methods

Syntax:
for(valueName in ObjectName){
// Code
}

Among them, valueName is the variable name, which holds the name of the attribute or method. Each Each cycle, the value of valueName will change.

Traverse the zhangsan object:

var zhangsan={}
zhangsan.name = "张三";
zhangsan.sex = "男";
zhangsan.say = function(){
        return "嗨!大家好,我来了。";
    }
zhangsan.contact = {
    tel : "029-81895644",
    qq : "1370753465",
    email : "itxueyuan@gmail.com"
}
var strTem="";  // 临时变量
for(value in zhangsan){
   strTem+=value+':'+zhangsan[value]+"\n";
}
alert(strTem);

Given any string, use the for in statement to count the number of characters appearing:

function charNum(str){
    var charObj={}
    for(i=0,len=str.length;i<len;i++){
        if(charObj[str[i]]){
            charObj[str[i]]++;
        }else{
            charObj[str[i]]=1;
        }
    }
    var strTem="";  // 临时变量
    for(value in charObj){
        strTem+='"'+value+'"的个数:'+charObj[value]+'\n';
    }
    return strTem;
}
charNum("http://www.it.org");
charNum("134775444637722991919");


Next Section
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <script>var zhangsan={} zhangsan.name = "张三"; zhangsan.sex = "男"; zhangsan.say = function(){ return "嗨!大家好,我来了。"; } zhangsan.contact = { tel : "029-81895644", qq : "1370753465", email : "itxueyuan@gmail.com" } var strTem=""; // 临时变量 for(value in zhangsan){ strTem+=value+':'+zhangsan[value]+"\n"; } alert(strTem);</script> </head> <body> </body> </html>
submitReset Code
ChapterCourseware