Web开发(初级)- python、JavaScript及jQuery循环语句

循环语句

1、概述

    python中循环语句有两种,while,for;python

    JavaScript中循环语句有四种,while,do/while,for,for/inide

    jQuery循环语句each函数

2、python循环语句


2.1 for 循环this

# a、

li = [1, 2, 3, 4]
for i in li:
    print(i)
# b、

li = [1, 2, 3, 4]
for i, j in enumerate(li, 1):
    print(i, j)
    
# enumerate(li, 1)中的 1 表明索引从 1 开始,默认为空,表明从 0 开始
# c、

li1 = [1, 3, 5, 7]
li2 = [2, 4, 6, 8]
for i, j in zip(li1, li2):
    print(i, j)
# d、不要经过 dic.items()来循环字典,效率会很是低

dic = {'a': 1, 'b': 2}
for k in dic:
    print(k, dic.get(k))
    
# 上述代码中,至关于对字典的key进行循环,等价于下面的代码:

dic={'a': 1, 'b': 2}
for k in dic.keys():
    print(k, dic.get(k))
    
# 对于值的循环,即 for v in dic.values() ...


2.2 while循环

while True:
    pass
    
# 在python中除了none、''、[]、{}、()、False,其余均为真值,即为True。

# 对于循环判断:eg. flag
# 判断是否为真:while flag:
# 判断是否为假:while not flag:

3、JavaScript循环语句

a、while循环

var count = 0;
while(count < 10){
    console.log(count);
    count ++;
}

# JavaScript定义局部变量用var

b、do/while

do{
   代码块;
}while(条件语句)

c、for

var a = document.getElementById('key').children;
for(var i=0; i<a.length; i++){
    var inp=a[i];
    var at=inp.getAttribute('type');
    if(at=='text'){
        inp.setAttribute('value', '123');
    }
} 

# 获取id='key'下全部type='text'的标签并设置value值等于'123'.

d、for  in

var c1 = document.getElementById('i1').getElementsByTagName('input');
for(var i in c1){
    if(c1[i].checked){
      c1[i].checked=false;
  }else{
      c1[i].checked=true;
  }
}

4、jQuery循环语句

each语句:spa

$(':text').each(function(){
    console.log($(this).val()) ;
});

# $(':text') ==> $('input[type="text"]')

语法规则:标签集合.each(匿名函数)orm

    上述代码的意思是:获取全部inp标签中type='text',的标签,并对其进行循环,每次打印它的值。索引

    jQuery中跳出循环用return:ip

        return true:退出本次循环,执行下次循环,至关于其它语言的continue;get

        return false:退出本层循环,即退出当前each,至关于其它语言的break;input

相关文章
相关标签/搜索