0
点赞
收藏
分享

微信扫一扫

JS基础(二)

1、函数

JS的函数基本使用如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>函数的基本使用</title>
    <script>
        //定义函数
        function add(a,b){
            return a+b;
        }
        //调用函数
        var result = add(1,2);
        alert(result);

        //也可以写成如下的形式
        let result1 = function(a,b){
            return a + b;
        }
        
        document.write(result1(1,2));

    </script>

</head>
<body>
    
</body>
</html>
2、JS中的对象

2.1、数组

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS对象</title>
    <script>
        // 创建数组
        let myarray = [1,2,3,4,5];
        //遍历数组
        for (let index = 0; index < myarray.length; index++) {
            const element = myarray[index];
            document.write(element);    
        }
        
        document.write("</br>")

        //数组中常见的方法
        //foreach:只遍历数组中有值的元素
        myarray.forEach(function(a){
            document.write(a);
        });

        document.write("</br>")

        //简写
        myarray.forEach((a) =>{
            document.write(a);
        });


    </script>

</head>
<body>
    
</body>
</html>
举报

相关推荐

0 条评论