JavaScript二

2023-12-29 23:39:43

目录

流程控制

?if判断

while循环

do while

for循环

forEach

for in?

Map与set

iterator


流程控制

?if判断

    <script>
        'use strict'
        var age = 5;
        if(age <= 3){
            alert("haha");
        }else if(age <= 5){
            alert("hi world");
        }else{
            alert("hello world");
        }
    </script>

while循环

    <script>
        'use strict'
        var age = 5;
        while(age < 100){
            age++;
            console.log(age);
        }
    </script>

do while

    <script>
        'use strict'
        var age = 5;
        do{
            age++;
            console.log(age);
        }while (age < 100);
    </script>

for循环

    <script>
        'use strict'
        for (let i = 0; i < 100; i++) {
            console.log(i);
        }
    </script>

forEach

    <script>
        'use strict'
        var arr = [1,2,3,4,5,6,6,7,8];
        arr.forEach(function (value) {
            console.log(value);
        });
    </script>

for in?

输出下标

    <script>
        'use strict'
        var arr = [12,23,3,44,5,6,26,57,8];
        for(var num in arr){
            console.log(arr[num]);
        }
    </script>

Map与set

?Map?

查找键对应的值

    <script>
        'use strict'
        var map = new Map([['tom',100],['jack',90],['hi',80]]);
        var sco = map.get('tom');
        console.log(sco);
    </script>

新增或者修改元素

    <script>
        'use strict'
        var map = new Map([['tom',100],['jack',90],['hi',80]]);
        map.set('admin',123456);
        var sco = map.get('admin');
        console.log(sco);
    </script>

删除元素

    <script>
        'use strict'
        var map = new Map([['tom',100],['jack',90],['hi',80]]);
        map.delete('tom');
        console.log(map);
    </script>

Set

?可以去重

    <script>
        'use strict'
        var set = new Set([1,1,1,2,34,4]);
        console.log(set);
    </script>

增加元素

    <script>
        'use strict'
        var set = new Set([1,1,1,2,34,4]);
        set.add(5);
        console.log(set);
    </script>

删除元素

    <script>
        'use strict'
        var set = new Set([1,1,1,2,34,4]);
        set.delete(5);
        console.log(set);
    </script>

查找是否包含元素

    <script>
        'use strict'
        var set = new Set([1,1,1,2,34,4]);
        console.log(set.has(1));
    </script>

iterator

推荐使用for of 进行遍历?

?遍历数组

    <script>
        'use strict'
        var arr = [11,22,3,4,5];
        for(var x of arr)console.log(x);
    </script>

遍历map

    <script>
        'use strict'
        var map = new Map([['tom',100],['jack',90],['hi',80]]);
        for(let x of map)console.log(x);
    </script>

遍历set

    <script>
        'use strict'
        let set = new Set([1,1,1,2,34,4]);
        for(let x of set)console.log(x);
    </script>

文章来源:https://blog.csdn.net/m0_72832574/article/details/135256437
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。