数值、文本、图形、音频、视频…
变量。 var Number。js 不区分小数和整数。
123// 整数。 123 123.1// 小数。 123.1 1.23e3// 科学计数法。 1230 -99// 负数。 -99 NaN// not a number. NaN Infinity// 无限大。 字符串。‘abc’, “abc”。
布尔。true, false。
逻辑运算。&& || !
比较运算符。 = ==(值一样)。 ===(类型一样,值一样)。NaN 与所有的数值都不相等,包括自己。
isNaN(NaN)。
NaN == NaN false NaN === NaN false isNaN(NaN) true 尽量避免使用浮点数进行运算。 console.log((1 / 3) === (1 - 2 / 3))/*false.*/null 和 undefined。
数组。
// 保证代码可读性,尽量使用 []。 var arr = [1, 2, 3, 4, 5, 'hello', null, true]; new Array(1, 2, 3, 4, 5, 'hello', null, true);数组下标,如果越界,就会
undefined 对象。对象是大括号,数组是中括号。
// Person person = new Person(); var person = { name: 'geek', age: 3, tags: ['js', 'java', 'web', '...'] } person.name "geek"
单引号 or 双引号。 ’ \n \t \u4e2d(中)。\u####。Unicode 字符。 \x41。ASCII 字符。
多行字符串。 var msg = ` hello, world ` var name = 'Geek'; var age = 3; var msg = ` hello, ${name} ` 大小写。 var student = 'student'; undefined console.log(student.length); VM184:1 7 undefined console.log(student[0]); VM218:1 s undefined console.log(student.toUpperCase); VM249:1 ƒ toUpperCase() { [native code] } undefined console.log(student.toUpperCase()); VM261:1 STUDENT undefined substring。 console.log(student.substr); VM368:1 ƒ substr() { [native code] } undefined console.log(student.substr(0,2)); VM393:1 st undefined console.log(student.substring(0,2)); VM419:1 st undefinedArray 可以包含任意数据类型。
var arr = [0, 1, 2, 3, 4 ,5, 6] undefined console.log(arr) VM524:1 (7) [0, 1, 2, 3, 4, 5, 6]0: 01: 12: 23: 34: 45: 56: 6length: 7__proto__: Array(0) undefined arr.length 7 arr[0] = 1 1 arr (7) [1, 1, 2, 3, 4, 5, 6] arr.length = 10 10 arr (10) [1, 1, 2, 3, 4, 5, 6, empty × 3] arr[9] undefined给 arr.length 赋值,数据大小就会发生变化。
indexOf();。 var arr = [0, 1, 2, 3, 4 ,5, 6, '1', '2'] undefined arr.indexOf(1) 1 arr.indexOf('1') 7 slice();。 arr.slice(1, 5) (4) [1, 2, 3, 4] push(); pop();。尾部。 arr (10) [0, 1, 2, 3, 4, 5, 6, "1", "2", "a"] arr.push('a') 10 arr.push('b') 11 arr.pop() "b" arr (10) [0, 1, 2, 3, 4, 5, 6, "1", "2", "a"] shift(); unshift();。头部。 arr (10) [0, 1, 2, 3, 4, 5, 6, "1", "2", "a"] arr.unshift('a', 'b') 12 arr (12) ["a", "b", 0, 1, 2, 3, 4, 5, 6, "1", "2", "a"] arr.shift() "a" arr.shift() "b" arr (10) [0, 1, 2, 3, 4, 5, 6, "1", "2", "a"] sort(); 排序。 arr (10) [0, 1, 2, 3, 4, 5, 6, "1", "2", "a"] arr.sort() (10) [0, 1, "1", 2, "2", 3, 4, 5, 6, "a"] arr.reverse() (10) ["a", 6, 5, 4, 3, "2", 2, "1", 1, 0]reverse();。
concat();。返回一个新数据。
arr.concat('C', 'B', 'A') (7) ["a", 6, 5, 4, "C", "B", "A"] arr (4) ["a", 6, 5, 4] join();。 arr.join('-') "a-6-5-4" arr (4) ["a", 6, 5, 4] 多维数组。 arr = [[1, 2], [3, 4], ['1', '2']] (3) [Array(2), Array(2), Array(2)] arr[1][1] 4return ~ 函数结束,返回结果。
如果没有 return,函数执行完也会返回结果 ~ undefined。
匿名函数,可以把返回值赋值给 abs,通过 abs 就可以调用函数。
let abs = function (x) { if (x >= 0) { return x; } else { return -x; } }; abs() NaN abs(-1) 1 abs(1) 1 abs(1,2,3) 1 如果没有传递参数。 let abs = function (x) { // 手动抛出异常。 if (typeof x !== 'number') { throw 'Not a number.' } if (x >= 0) { return x; } else { return -x; } };arguments 是 js 免费赠送的关键词。
传递进来的所有参数,是一个数组。
let abs = function (x) { console.log('x =< ' + x); for (let argumentsKey in arguments) { console.log(argumentsKey); } // 手动抛出异常。 if (typeof x !== 'number') { throw 'Not a number.' } if (x >= 0) { return x; } else { return -x; } }; abs(1, 2, 3, 4, 5, 6, 7, 8, 9) x =< 1 0 1 2 3 4 5 6 7 8 1ES6 引入的新特性,获取除了已经定义的参数之外的所有参数。
if (arguments.length > 2) { for (let i = 2; i < arguments.length; i++) { } }↓ ↓ ↓
function aaa(a, b, ...rest) { console.log('a => ' + a); console.log('b => ' + b); console.log(rest); // if (arguments.length > 2) { // for (let i = 2; i < arguments.length; i++) { // // } // } }var 定义的变量是由作用域的。
函数体中声明,函数体外是不可使用的。(非要实现,闭包)。
<script> function geek() { var x = 1; x = x + 1; } x = x + 2;// Uncaught ReferenceError: x is not defined </script>js 执行引擎,自动提升了 y 的声明,但是不会提升变量 y 的赋值。
养成规范:所有变量的声明都放在函数的最前面。
function geek() { var x = 'x' + y; console.log(x); y = 'y'; }默认所有的全局变量,都会自动绑定在 window 对象下。
var x = 'xxx'; // alert(x); window.alert(x); // alert(window.x); window.alert(window.x);alert(); 这个函数本身也是 window 的一个对象。
let x = 'xxx'; window.alert(x); let old_alert = window.alert; old_alert(x); window.alert = function () { }; // 失效。 window.alert(123); // 恢复。 window.alert = old_alert;JavaScript 实际上只有一个全局作用于域,任何变量(函数也可以视为变量)。假设没有在函数作用范围内找到,就会向外查找,如果在全局作用域都没有找到。报错 ReferenceError。
把自己的代码全部放入自己定义的唯一命名空间中,降低全局命名中的冲突。
// 唯一全局变量。 var geekApp = {}; // 定义全局变量。 geekApp.name = 'geek'; geekApp.add = function (a, b) { return a + b; } function aaa() { for (var i = 0; i < 100; i++) { console.log(i); } console.log(i);// 101 } function bbb() { for (let i = 0; i < 100; i++) { console.log(i); } console.log(i);// Uncaught ReferenceError: i is not defined }ES6 之前,定义常量:只有用全部大写字母命名的变量就是常量,建议不要修改 ta 的值。
(只读变量)。
JSON(JavaScript Object Notation, JS 对象简谱)是一种轻量级的数据交换格式。它基于 ECMAScript(欧洲计算机协会制定的 js 规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
JavaScript 中,一切皆对象。任何 js 支持的类都可以用 JSON 来表示。
格式。
对象 ~ {}。 数组 ~ []。 键值对 ~ key: value。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> let user = { name: 'geek', age: 3, gender: '男' }; console.log(user); // 对象转化为 JSON 字符串。 let jsonUser = JSON.stringify(user); console.log(jsonUser); // json 字符串转化为对象。 let obj = JSON.parse('{"name": "geek", "age": 3, "gender": "男"}'); console.log(obj); </script> </head> <body> </body> </html>原生的 js 写法 ~ xhr 异步请求。(XMLHttpRequest)。
jQuery 封装好的方法。$(’#name’).ajax();
aious 请求。
class 关键字是在 es6 引入的。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> function Student(name) { this.name = name; } // 给 student 对象增加一个方法。 Student.prototype.hello = function () { alert('Hello.'); }; // es 6。~ ~ ~ ~ ~ ~ ~ class Student { constructor(name) { this.name = name; } hello() { alert('hello'); } } let xiaoming = new Student('xiaoming'); let xiaohong = new Student('xiaohong'); </script> </body> </html> 继承。 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> // es 6。~ ~ ~ ~ ~ ~ ~ class Student { constructor(name) { this.name = name; } hello() { alert('hello'); } } class Pupil extends Student { constructor(name, grade) { super(name); this.grade = grade; } myGrade() { alert('我是一名小学生。') } } let xiaoming = new Student('xiaoming'); let xiaohong = new Pupil('xiaohong', 1); </script> </body> </html>__proto__
浏览器页面就是一个 Dom 树形结构。
我们获得了某个节点,假设这个 dom 节点是空的,我们通过 innerHTML 就可以增加一个元素了,但是这个 dom 节点已经存在元素了,我们就不能这么干了,会产生覆盖。
追加。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p id="js">JavaScript</p> <div id="list"> <p id="ee">JavaEE</p> <p id="se">JavaSE</p> <p id="me">JavaME</p> </div> <script> let js = document.getElementById('js'); let list = document.getElementById('list'); list.appendChild(js); </script> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p id="js">JavaScript</p> <div id="list"> <p id="ee">JavaEE</p> <p id="se">JavaSE</p> <p id="me">JavaME</p> </div> <script> let js = document.getElementById('js'); let list = document.getElementById('list'); // list.appendChild(js); // 创建一个新节点。 let newP = document.createElement('p'); newP.id = 'newP'; newP.innerText = 'Hello, geek'; list.appendChild(newP); </script> </body> </html> let myStyle = document.createElement('style'); myStyle.setAttribute('type', 'text/css'); myStyle.innerHTML = 'body {background-color: deepskyblue}'; document.getElementsByTagName('head')[0].appendChild(myStyle)先获取父节点,再通过父节点删除自己。
<div id="father"> <h1>标题</h1> <p id="p1">p1</p> <p class="p2">p2</p> </div> <script> let self = document.getElementById('p1'); let father = p1.parentElement; father.removeChild(self); father.removeChild(p1) <p id="p1">p1</p> father.removeChild(father.children[0]); father.removeChild(father.children[0]); father.removeChild(father.children[0]); </script>Browser Object Model。
JavaScript 诞生就是为了能够让 ta 在浏览器中运行。
IE 6~11 Chrome Safari Firefox
三方。QQ 浏览器。 360 浏览器。
浏览器窗口。
window.alert(1) undefined window.innerHeight 510 window.innerWidth 1367 window.outerHeight 960 window.outerWidth 1367封装了浏览器信息。
navigator.appName "Netscape" navigator.appVersion "5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" navigator.userAgent "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" navigator Navigator {vendorSub: "", productSub: "20030107", vendor: "Google Inc.", maxTouchPoints: 0, hardwareConcurrency: 1, …} vendorSub: "" productSub: "20030107" vendor: "Google Inc." maxTouchPoints: 0 hardwareConcurrency: 1 cookieEnabled: true appCodeName: "Mozilla" appName: "Netscape" appVersion: "5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" platform: "Linux x86_64" product: "Gecko" userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" language: "en-US" languages: (2) ["en-US", "en"] onLine: true doNotTrack: null geolocation: Geolocation {} mediaCapabilities: MediaCapabilities {} connection: NetworkInformation {onchange: null, effectiveType: "4g", rtt: 50, downlink: 10, saveData: false} plugins: PluginArray {0: Plugin, 1: Plugin, Chromium PDF Plugin: Plugin, Chromium PDF Viewer: Plugin, length: 2} mimeTypes: MimeTypeArray {0: MimeType, 1: MimeType, application/pdf: MimeType, application/x-google-chrome-pdf: MimeType, length: 2} webkitTemporaryStorage: DeprecatedStorageQuota {} webkitPersistentStorage: DeprecatedStorageQuota {} userActivation: UserActivation {hasBeenActive: true, isActive: true} mediaSession: MediaSession {metadata: null, playbackState: "none"} permissions: Permissions {} deviceMemory: 4 clipboard: Clipboard {} credentials: CredentialsContainer {} keyboard: Keyboard {} locks: LockManager {} mediaDevices: MediaDevices {ondevicechange: null} serviceWorker: ServiceWorkerContainer {ready: Promise, controller: null, oncontrollerchange: null, onmessage: null} storage: StorageManager {} presentation: Presentation {receiver: null, defaultRequest: null} usb: USB {onconnect: null, ondisconnect: null} xr: XR {ondevicechange: null} __proto__: Navigator当前页面。
HTML 文档树。
document.title "写文章-博客"获取具体的文档树结点。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <dl id="app"> <dt>Java</dt> <dt>JavaSE</dt> <dt>JavaEE</dt> </dl> </body> </html> <script> let dl = document.getElementById('app'); </script> 获取 cookie。 document.cookiehistory.back() history.forward()
隐藏域存储加密后的密码。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/blueimp-md5/2.16.0/js/md5.min.js"></script> </head> <body> <form action="https://www.baidu.com/" method="post" onsubmit="return aaa()"> <p> <span>用户名:</span> <input id="username" type="text" name="username"> </p> <p> <span>密码:</span> <input id="input-password" type="text"> </p> <input type="hidden" id="md5-password" name="password"> <!-- 绑定事件。--> <button type="submit">提交</button> </form> <script> function aaa() { // alert(111) let uname = document.getElementById('username'); let pwd = document.getElementById('input-password'); let md5pwd = document.getElementById('md5-password'); md5pwd.value = md5(pwd.value); return true; } </script> </body> </html>jQuery 是一个 JavaScript 库。
jQuery 极大地简化了 JavaScript 编程。
jQuery 很容易学习。
https://jquery.cuishifeng.cn/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--<script src='lib/jquery-3.5.1.min.js'></script>--> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <!-- $(selector).action(); --> <a href="" id="test-jquery">点我</a> <script> document.getElementById('test-jquery'); $('#test-jquery').click(function () { alert('hello, jQuery'); }) </script> </body> </html>本质。
display: none;
other。 $(document).width ƒ (e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentE… $(document).width() 1367 $(document).height() 510