JavaScript 语法

张开发
2026/4/14 22:37:43 15 分钟阅读

分享文章

JavaScript 语法
JavaScript 语法学习笔记1. 基础语法变量声明// var - 函数作用域存在变量提升varnameJohn;// let - 块级作用域不存在变量提升letage25;// const - 块级作用域声明时必须初始化不能重新赋值constPI3.14159;数据类型// 基本数据类型letstrHello;// Stringletnum42;// Numberletbooltrue;// Booleanletundef;// Undefinedletnulnull;// NullletsymSymbol(id);// Symbolletbig9007199254740991n;// BigInt// 引用数据类型letobj{name:John};// Objectletarr[1,2,3];// Arrayletfuncfunction(){};// Function运算符// 算术运算符letsum105;// 15letdiff10-5;// 5letproduct10*5;// 50letquotient10/5;// 2letremainder10%3;// 1// 比较运算符console.log(105);// trueconsole.log(1010);// true (类型转换)console.log(1010);// false (严格相等)// 逻辑运算符console.log(truefalse);// falseconsole.log(true||false);// trueconsole.log(!true);// false2. 控制结构条件语句// if-elseletscore85;if(score90){console.log(优秀);}elseif(score80){console.log(良好);}else{console.log(需要努力);}// 三元运算符letstatusscore60?及格:不及格;// switchletday3;switch(day){case1:console.log(星期一);break;case2:console.log(星期二);break;case3:console.log(星期三);break;default:console.log(其他);}循环语句// for 循环for(leti0;i5;i){console.log(i);}// while 循环letcount0;while(count5){console.log(count);count;}// do-while 循环letnum0;do{console.log(num);num;}while(num5);// for...of (遍历可迭代对象)letfruits[苹果,香蕉,橙子];for(letfruitoffruits){console.log(fruit);}// for...in (遍历对象属性)letperson{name:John,age:30};for(letkeyinperson){console.log(${key}:${person[key]});}3. 函数函数声明// 传统函数声明functionadd(a,b){returnab;}// 函数表达式constmultiplyfunction(a,b){returna*b;};// 箭头函数constdivide(a,b)a/b;// 默认参数functiongreet(nameGuest){returnHello,${name}!;}// 剩余参数functionsum(...numbers){returnnumbers.reduce((acc,num)accnum,0);}// 解构参数functionprintCoords({x,y}){console.log(x:${x}, y:${y});}作用域与闭包// 全局作用域letglobalVarIm global;functionouter(){// 函数作用域letouterVarIm in outer;functioninner(){// 闭包可以访问外层函数的变量console.log(outerVar);console.log(globalVar);}returninner;}constinnerFuncouter();innerFunc();// 输出Im in outer, Im global4. 对象对象创建// 对象字面量letperson{name:John,age:30,greet:function(){console.log(Hello, Im${this.name});}};// 构造函数functionPerson(name,age){this.namename;this.ageage;}Person.prototype.greetfunction(){console.log(Hello, Im${this.name});};letperson2newPerson(Jane,25);// ES6 类classAnimal{constructor(name){this.namename;}speak(){console.log(${this.name}makes a noise.);}}classDogextendsAnimal{speak(){console.log(${this.name}barks.);}}letdognewDog(Rex);dog.speak();// Rex barks.对象方法letobj{a:1,b:2,c:3};// Object.keys() - 获取所有键console.log(Object.keys(obj));// [a, b, c]// Object.values() - 获取所有值console.log(Object.values(obj));// [1, 2, 3]// Object.entries() - 获取所有键值对console.log(Object.entries(obj));// [[a, 1], [b, 2], [c, 3]]// 扩展运算符letnewObj{...obj,d:4};// 解构赋值let{a,b}obj;5. 数组数组方法letnumbers[1,2,3,4,5];// map - 转换数组letdoublednumbers.map(nn*2);// [2, 4, 6, 8, 10]// filter - 过滤数组letevensnumbers.filter(nn%20);// [2, 4]// reduce - 归约数组letsumnumbers.reduce((acc,n)accn,0);// 15// forEach - 遍历数组numbers.forEach(nconsole.log(n));// find - 查找第一个匹配元素letfoundnumbers.find(nn3);// 4// some - 检查是否有元素满足条件lethasEvennumbers.some(nn%20);// true// every - 检查所有元素是否满足条件letallPositivenumbers.every(nn0);// true// slice - 截取数组letslicednumbers.slice(1,3);// [2, 3]// splice - 修改数组letarr[1,2,3,4,5];arr.splice(2,1,10);// [1, 2, 10, 4, 5]6. 异步编程Promise// 创建 PromiseletpromisenewPromise((resolve,reject){setTimeout((){letsuccesstrue;if(success){resolve(操作成功!);}else{reject(操作失败!);}},1000);});// 使用 Promisepromise.then(resultconsole.log(result)).catch(errorconsole.error(error)).finally(()console.log(操作完成));// Promise 链fetch(/api/data).then(responseresponse.json()).then(dataconsole.log(data)).catch(errorconsole.error(error));// Promise.all - 并行执行多个 PromisePromise.all([promise1,promise2,promise3]).then(resultsconsole.log(results)).catch(errorconsole.error(error));async/await// async 函数asyncfunctionfetchData(){try{letresponseawaitfetch(/api/data);letdataawaitresponse.json();console.log(data);returndata;}catch(error){console.error(error);}}// 并行执行多个异步操作asyncfunctionfetchMultiple(){let[data1,data2]awaitPromise.all([fetch(/api/data1).then(rr.json()),fetch(/api/data2).then(rr.json())]);return{data1,data2};}7. ES6 新特性模板字符串letnameJohn;letage30;letgreetingHello, my name is${name}and Im${age}years old.;letmultiLineThis is a multi-line string.;解构赋值// 数组解构let[a,b,...rest][1,2,3,4,5];console.log(a,b,rest);// 1, 2, [3, 4, 5]// 对象解构let{name,age}{name:John,age:30,city:NYC};console.log(name,age);// John, 30// 重命名let{name:userName,age:userAge}{name:John,age:30};console.log(userName,userAge);// John, 30模块化// 导出模块 (module.js)exportconstPI3.14159;exportfunctioncalculateCircleArea(radius){returnPI*radius*radius;}exportdefaultclassCircle{constructor(radius){this.radiusradius;}}// 导入模块 (main.js)importCircle,{PI,calculateCircleArea}from./module.js;import*asMathUtilsfrom./module.js;可选链操作符letuser{name:John,address:{city:NYC}};// 安全访问嵌套属性letcityuser?.address?.city;letzipuser?.address?.zipCode;// undefined不会报错空值合并运算符letvaluenull;letresultvalue??默认值;// 默认值letcount0;letdisplayCountcount??10;// 0 (因为 0 不是 null 或 undefined)8. 错误处理// try-catch-finallytry{letresultriskyOperation();console.log(result);}catch(error){console.error(发生错误:,error.message);}finally{console.log(无论是否发生错误都会执行);}// 自定义错误classCustomErrorextendsError{constructor(message){super(message);this.nameCustomError;}}functionvalidateAge(age){if(age0){thrownewCustomError(年龄不能为负数);}returntrue;}9. 常用内置对象// DateletnownewDate();console.log(now.getFullYear());console.log(now.getMonth()1);// 月份从 0 开始console.log(now.getDate());// Mathconsole.log(Math.PI);console.log(Math.random());console.log(Math.floor(4.7));console.log(Math.ceil(4.2));console.log(Math.round(4.5));// JSONletobj{name:John,age:30};letjsonStrJSON.stringify(obj);letparsedObjJSON.parse(jsonStr);// RegExpletpattern/\d/;console.log(pattern.test(abc123));// trueconsole.log(abc123.match(pattern));// [123]10. 最佳实践// 1. 使用 const 和 let避免使用 varconstMAX_USERS100;letcurrentUsernull;// 2. 使用严格模式use strict;// 3. 使用箭头函数处理 thisclassCounter{constructor(){this.count0;setInterval((){this.count;// 箭头函数保留 this},1000);}}// 4. 使用解构赋值简化代码functionprocessUser({name,age,email}){// 直接使用解构后的变量}// 5. 使用模板字符串constmessageHello,${name}! You are${age}years old.;// 6. 使用扩展运算符constnewArray[...oldArray,newItem];constnewObj{...oldObj,newProp:value};// 7. 使用可选链和空值合并constcityuser?.address?.city??Unknown;这份笔记涵盖了 JavaScript 的核心语法和常用特性适合初学者快速掌握 JavaScript 编程。建议结合实际项目练习加深理解。

更多文章