博主信息
博文 22
粉丝 0
评论 0
访问量 19602
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
JS第一课
杰西卡妈妈
原创
741人浏览过

1. js引入方式

1) 行内脚本: on…

  1. <button onclick="document.querySelector('h1').classList.toggle('active')">Click</button>
  2. <button onclick="toggleColor()">Click</button>

2) 内部脚本, 在<script></script>中

  1. <script>
  2. function toggleColor() {
  3. document.querySelector("h1").classList.toggle("active");
  4. }
  5. </script>

3) 外部脚本: toggle.js

<script src="toggle.js"></script>
#### 效果全部是一样


## 2. 变量与常量的声明与使用方式
#### 1) 变量声明:let userName
userName =..
console.log(userName)
userName =..
console.log(userName)
userName = null;
console.log(userName)
#### 2) 常量通常全大写,多个单词之间使用下划线
const GENDER = “female”
console.log(GENDER)
#### 3) 使用方式
只允许字母,数字,下划线,$,并且禁止数字开头
- 驼峰式: userName, unitPrice
- 帕斯卡式: UserName, UnitPrice,大驼峰式,用在类/构造函数
- 蛇形式: user_name, unit_price
- 匈牙利式: 将数据类型放在变量的最前面
js推荐使用: userName, unitPrice

## 3. 函数与高阶函数 Higher order function
- 函数一定有一个返回值;
- 函数可以提升,后面写的会覆盖前面的
- 如果不希望函数提升,必须用匿名函数=>声明再使用
<script>
function getName(name) {
return “welcome to: “ + name;
}
console.log(getName(“Peter”));
</script>

let sum =function (a,b) {
return a + b;
};

  1. console.log(sum(1,6));
  • 默认参数
    sum = function (a, b = 10) {
    return a + b;
    }
    console.log(sum(1));
  • 如果很多数相加,用归并参数,rest语法(…arr)
    sum = function (…arr) {
    console.log(arr);
    return arr.reduce((p, c) => p + c);
    }
    console.log(sum(1, 2, 3, 4, 5, 6, 7));

  • 返回多个值,使用数组array或对象object
    function getUser() {
    return [10, “admin”, “admin@abc.com”];
    }
    function getUser() {
    return { id: 10, username: “admin”, email: “admin@abc.com”}
    }

  • 高阶函数: 回调函数 and 偏函数

  • Currying 柯里化: 多个单一参数,返回同一个值
    let f1 = sum(1, 2);

    1. console.log(typeof f1);
    2. console.log(f1(3, 4));
    3. sum = function (a) {
    4. return function (b) {
    5. return function (c) {
    6. return function (d) {
    7. return a + b + c + d;
    8. };
    9. };
    10. };
    11. };
    12. let res = sum(1)(2)(3)(4);
    13. console.log("res =", res);
    • 纯函数

      5. 箭头函数 Arrow function =>

      匿名函数常用; 如果函数中要使用到this,就不要用箭头函数,不能当构造函数用

6. 立即执行函数

  • 声明调用二合一, 把整个函数放进一对大括号声明后直接执行。
  • 一旦将代码块用一个立即执行函数套住,那么内部声明的变量b就不断泄露到全局中
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学