JS-07-JS控制语句与数组
JS-07-JS控制语句与数组
1.JS中有哪些控制语句?
JS中有如下控制语句:
- 1.if
- 2.switch
- 3.for
- 4.while
- 5.do...while
- 6.continue
- 7.break
- 8.for...in(了解)
- 9.with(了解)
用法与java一致。
2.JS数组
2.1JS中数组的创建
JS中数组的元素类型随意,个数随意,用中括号包含元素。
var arr = [1,3.14,"abc",true];
2.2遍历JS数组
用普通for循环遍历JS数组
<script type="text/javascript">
    //数组的创建
    var arr = [1,3.14,"abc",true];
    //用普通for循环遍历数组
    for(var i = 0;i < arr.length;i++) {
        alert(arr[i]);
    }
</script>

3.for...in语句
3.1for...in语句可以遍历JS数组
<script type="text/javascript">
    //数组的创建
    //用for循环遍历
    var arr = [1,3.14,"abc",true];
    //用for...in语句遍历
    for(var i in arr) {
        alert(arr[i]);
    }
</script>

3.2for...in语句还可以获取对象中的属性值
 <script type="text/javascript">
     function User(username,password) {
     	this.username = username;
     	this.password = password;
 	}
	//创建对象
	var user1 = new User("张三",123);
    //获取对象的值:
    alert(user1["username"] + "," + user1["password"]);
    //使用for...in获取对象的值
    for(var i in user1) {
        //alert(i);//属性名username、password
        //alert(typeof i);//数据类型string、string。说明i是字符串"username"、"password"
        alert(user1[i])
    }
</script>

4.with语句
<script type="text/javascript">
    function User(username,password) {
    	this.username = username;
    	this.password = password;
    }
    var user1 = new User("张三",123);
    alert(user1.username + "," + user1.password);
    //with语句
    with(user1) {
        //默认user1.username
        alert(username + "," + password);
    }
</script>


 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号