1. JavaScript概述
JavaScript是一种广泛使用的脚本语言,主要用于Web前端开发,也可用于后端开发(如Node.js)。JavaScript可以为网页添加交互性,处理表单验证,创建动态内容,以及与服务器进行通信。更多学习教程www.fgedu.net.cn
2. JavaScript开发环境搭建
JavaScript开发环境相对简单,只需要一个文本编辑器和浏览器即可开始。对于更复杂的项目,可以使用Node.js和相关工具。
# 1. 安装Node.js
# 下载并安装Node.js(包含npm)
# 访问 https://nodejs.org/ 下载适合你系统的版本
# 验证安装
$ node –version
v18.17.0
$ npm –version
9.6.7
# 2. 安装包管理工具
# 可选:安装yarn
$ npm install -g yarn
# 验证yarn
$ yarn –version
1.22.19
# 3. 安装代码编辑器
# 推荐使用VS Code、Sublime Text、Atom等
# 4. 初始化项目
$ mkdir my-js-project
$ cd my-js-project
$ npm init -y
# 5. 安装依赖
$ npm install lodash axios
# 6. 创建示例文件
$ touch index.js
# 7. 运行JavaScript文件
$ node index.js
3. JavaScript基础知识
JavaScript基础知识包括变量、数据类型、运算符、控制语句等。学习交流加群风哥微信: itpux-com
// 变量声明
var name = “JavaScript Developer”;
let age = 25;
const salary = 5000.0;
// 输出信息
console.log(`Hello, ${name}!`);
console.log(`Age: ${age}`);
console.log(`Salary: ${salary}`);
// 控制语句
if (age >= 18) {
console.log(“Adult”);
} else {
console.log(“Minor”);
}
// 循环语句
console.log(“Counting from 1 to 5:”);
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// 函数定义与调用
function add(a, b) {
return a + b;
}
let result = add(10, 20);
console.log(`Sum: ${result}`);
// 数组操作
let fruits = ["Apple", "Banana", "Orange"];
console.log(`Fruits: ${fruits}`);
fruits.push("Mango");
console.log(`Fruits after push: ${fruits}`);
console.log(`First fruit: ${fruits[0]}`);
// 对象操作
let person = { name: "John", age: 30, city: "New York" };
console.log(`Person: ${JSON.stringify(person)}`);
console.log(`Name: ${person.name}`);
person.age = 31;
console.log(`Person after update: ${JSON.stringify(person)}`);
// 输出:
// Hello, JavaScript Developer!
// Age: 25
// Salary: 5000
// Adult
// Counting from 1 to 5:
// 1
// 2
// 3
// 4
// 5
// Sum: 30
// Fruits: Apple,Banana,Orange
// Fruits after push: Apple,Banana,Orange,Mango
// First fruit: Apple
// Person: {"name":"John","age":30,"city":"New York"}
// Name: John
// Person after update: {"name":"John","age":31,"city":"New York"}
4. 数据类型与操作
JavaScript支持多种数据类型,包括原始类型和引用类型。
// 原始类型
let string = “Hello, JavaScript!”;
let number = 42;
let boolean = true;
let nullValue = null;
let undefinedValue = undefined;
let symbol = Symbol(“unique”);
console.log(`String: ${string}, type: ${typeof string}`);
console.log(`Number: ${number}, type: ${typeof number}`);
console.log(`Boolean: ${boolean}, type: ${typeof boolean}`);
console.log(`Null: ${nullValue}, type: ${typeof nullValue}`); // 注意:null的类型是object
console.log(`Undefined: ${undefinedValue}, type: ${typeof undefinedValue}`);
console.log(`Symbol: ${symbol}, type: ${typeof symbol}`);
// 引用类型
let array = [1, 2, 3, 4, 5];
let object = { name: “Alice”, age: 28 };
let func = function() { return “Hello”; };
console.log(`Array: ${array}, type: ${typeof array}`);
console.log(`Object: ${JSON.stringify(object)}, type: ${typeof object}`);
console.log(`Function: ${func}, type: ${typeof func}`);
// 类型转换
let numStr = “42”;
let num = Number(numStr);
console.log(`String to number: ${num}, type: ${typeof num}`);
let boolNum = Number(true);
console.log(`Boolean to number: ${boolNum}`);
let numToStr = String(42);
console.log(`Number to string: ${numToStr}, type: ${typeof numToStr}`);
// 操作符
let a = 10;
let b = 5;
console.log(`a + b = ${a + b}`);
console.log(`a – b = ${a – b}`);
console.log(`a * b = ${a * b}`);
console.log(`a / b = ${a / b}`);
console.log(`a % b = ${a % b}`);
console.log(`a ** b = ${a ** b}`);
// 比较操作符
console.log(`a == b: ${a == b}`);
console.log(`a === b: ${a === b}`);
console.log(`a != b: ${a != b}`);
console.log(`a !== b: ${a !== b}`);
console.log(`a > b: ${a > b}`);
console.log(`a < b: ${a < b}`);
console.log(`a >= b: ${a >= b}`);
console.log(`a <= b: ${a <= b}`);
// 逻辑操作符
let x = true;
let y = false;
console.log(`x && y: ${x && y}`);
console.log(`x || y: ${x || y}`);
console.log(`!x: ${!x}`);
5. 控制流语句
JavaScript的控制流语句包括条件语句、循环语句等。
// if-else语句
let score = 85;
if (score >= 90) {
console.log(“Grade: A”);
} else if (score >= 80) {
console.log(“Grade: B”);
} else if (score >= 70) {
console.log(“Grade: C”);
} else if (score >= 60) {
console.log(“Grade: D”);
} else {
console.log(“Grade: F”);
}
// switch语句
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = “Monday”;
break;
case 2:
dayName = “Tuesday”;
break;
case 3:
dayName = “Wednesday”;
break;
case 4:
dayName = “Thursday”;
break;
case 5:
dayName = “Friday”;
break;
case 6:
dayName = “Saturday”;
break;
case 7:
dayName = “Sunday”;
break;
default:
dayName = “Invalid day”;
}
console.log(`Day: ${dayName}`);
// for循环
let fruits = [“Apple”, “Banana”, “Orange”, “Mango”];
console.log(“Fruits:”);
for (let i = 0; i < fruits.length; i++) {
console.log(`- ${fruits[i]}`);
}
// for...of循环
console.log("Fruits (for...of):");
for (let fruit of fruits) {
console.log(`- ${fruit}`);
}
// for...in循环
let person = { name: "Alice", age: 28, city: "London" };
console.log("Person properties:");
for (let property in person) {
console.log(`${property}: ${person[property]}`);
}
// while循环
let count = 1;
console.log("While loop:");
while (count <= 5) {
console.log(count);
count++;
}
// do...while循环
let num = 1;
console.log("Do...while loop:");
do {
console.log(num);
num++;
} while (num <= 5);
// break和continue
console.log("Break example:");
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
console.log("Continue example:");
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
6. 函数与作用域
JavaScript函数是可重用的代码块,作用域决定了变量的可访问性。学习交流加群风哥QQ113257174
// 函数声明
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet(“Alice”));
// 函数表达式
const calculateArea = function(length, width = 1) {
return length * width;
};
console.log(calculateArea(5, 3));
console.log(calculateArea(5)); // 使用默认参数
// 箭头函数
const sum = (a, b) => a + b;
console.log(sum(10, 20));
// 带多个语句的箭头函数
const multiply = (a, b) => {
const result = a * b;
return result;
};
console.log(multiply(5, 4));
// 作用域示例
let globalVar = “Global”;
function testScope() {
let localVar = “Local”;
console.log(`Global variable: ${globalVar}`);
console.log(`Local variable: ${localVar}`);
// 块级作用域
if (true) {
let blockVar = “Block”;
console.log(`Block variable: ${blockVar}`);
}
// console.log(`Block variable outside block: ${blockVar}`); // 会引发错误
}
testScope();
// console.log(`Local variable outside function: ${localVar}`); // 会引发错误
// 闭包
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
// 立即执行函数表达式 (IIFE)
(function() {
let privateVar = “Private”;
console.log(`IIFE private variable: ${privateVar}`);
})();
// console.log(`Private variable outside IIFE: ${privateVar}`); // 会引发错误
7. 对象与面向对象编程
JavaScript是一种基于对象的语言,支持面向对象编程。
// 对象字面量
let person = {
name: “John”,
age: 30,
greet: function() {
return `Hello, my name is ${this.name}`;
},
getAge: function() {
return this.age;
}
};
console.log(person.greet());
console.log(`Age: ${person.getAge()}`);
// 构造函数
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
return `Hello, my name is ${this.name}`;
};
Person.prototype.getAge = function() {
return this.age;
};
let person1 = new Person(“Alice”, 25);
let person2 = new Person(“Bob”, 30);
console.log(person1.greet());
console.log(person2.greet());
// ES6类
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
return `${this.name} is eating`;
}
sleep() {
return `${this.name} is sleeping`;
}
}
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age);
this.breed = breed;
}
bark() {
return `${this.name} is barking`;
}
// 重写父类方法
eat() {
return `${this.name} (${this.breed}) is eating bones`;
}
}
let dog = new Dog(“Buddy”, 3, “Golden Retriever”);
console.log(dog.eat());
console.log(dog.sleep());
console.log(dog.bark());
// 静态方法
class MathUtils {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
console.log(`5 + 3 = ${MathUtils.add(5, 3)}`);
console.log(`5 * 3 = ${MathUtils.multiply(5, 3)}`);
// getter和setter
class PersonClass {
constructor(name, age) {
this._name = name;
this._age = age;
}
get name() {
return this._name;
}
set name(newName) {
this._name = newName;
}
get age() {
return this._age;
}
set age(newAge) {
if (newAge >= 0) {
this._age = newAge;
}
}
}
let personObj = new PersonClass(“Charlie”, 20);
console.log(`Name: ${personObj.name}`);
console.log(`Age: ${personObj.age}`);
personObj.name = “David”;
personObj.age = 25;
console.log(`Updated name: ${personObj.name}`);
console.log(`Updated age: ${personObj.age}`);
8. DOM操作
DOM(Document Object Model)操作是JavaScript在浏览器中与HTML元素交互的方式。
// HTML结构示例
/*
Hello DOM
This is a paragraph.
This is another paragraph.
- Item 1
- Item 2
- Item 3
*/
// 选择元素
// 通过ID选择
const title = document.getElementById(“title”);
console.log(title.textContent);
// 通过类名选择
const paragraphs = document.getElementsByClassName(“paragraph”);
console.log(paragraphs.length);
// 通过标签名选择
const listItems = document.getElementsByTagName(“li”);
console.log(listItems.length);
// 通过CSS选择器选择
const container = document.querySelector(“#container”);
const firstParagraph = document.querySelector(“.paragraph”);
const allParagraphs = document.querySelectorAll(“.paragraph”);
// 修改元素
// 修改文本内容
title.textContent = “Hello JavaScript DOM”;
// 修改HTML内容
firstParagraph.innerHTML = “This is a modified paragraph.”;
// 修改样式
title.style.color = “blue”;
title.style.fontSize = “24px”;
// 添加/移除类
firstParagraph.classList.add(“highlight”);
firstParagraph.classList.remove(“paragraph”);
// 创建和添加元素
const newItem = document.createElement(“li”);
newItem.textContent = “Item 4”;
const list = document.getElementById(“list”);
list.appendChild(newItem);
// 插入元素
const newItem2 = document.createElement(“li”);
newItem2.textContent = “Item 0”;
list.insertBefore(newItem2, list.firstChild);
// 删除元素
list.removeChild(list.lastChild);
// 事件处理
const btn = document.getElementById(“btn”);
// 方式1:使用onclick属性
btn.onclick = function() {
alert(“Button clicked!”);
};
// 方式2:使用addEventListener
btn.addEventListener(“click”, function() {
console.log(“Button clicked!”);
});
// 方式3:使用箭头函数
btn.addEventListener(“click”, () => {
console.log(“Button clicked with arrow function!”);
});
// 事件冒泡和捕获
// 事件冒泡(从内到外)
// 事件捕获(从外到内)
// 阻止事件默认行为
const link = document.querySelector(“a”);
link.addEventListener(“click”, function(e) {
e.preventDefault();
console.log(“Link clicked, but default behavior prevented”);
});
9. 异步编程
JavaScript是单线程语言,但通过异步编程可以处理耗时操作,如网络请求、文件读写等。更多学习教程公众号风哥教程itpux_com
// 回调函数
function fetchData(callback) {
setTimeout(() => {
const data = { name: “Alice”, age: 25 };
callback(data);
}, 1000);
}
fetchData(function(data) {
console.log(“Callback data:”, data);
});
// Promise
function fetchDataPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
const data = { name: “Bob”, age: 30 };
resolve(data);
} else {
reject(new Error(“Failed to fetch data”));
}
}, 1000);
});
}
fetchDataPromise()
.then(data => {
console.log(“Promise resolved:”, data);
return “Processed data”;
})
.then(result => {
console.log(“Second then:”, result);
})
.catch(error => {
console.error(“Promise rejected:”, error);
})
.finally(() => {
console.log(“Promise completed”);
});
// async/await
async function fetchDataAsync() {
try {
const data = await fetchDataPromise();
console.log(“Async/await data:”, data);
return “Processed data”;
} catch (error) {
console.error(“Async/await error:”, error);
throw error;
} finally {
console.log(“Async/await completed”);
}
}
fetchDataAsync()
.then(result => {
console.log(“Async/await result:”, result);
})
.catch(error => {
console.error(“Async/await error caught:”, error);
});
// 并行执行Promise
const promise1 = fetchDataPromise();
const promise2 = new Promise(resolve => setTimeout(() => resolve(“Second promise”), 500));
Promise.all([promise1, promise2])
.then(results => {
console.log(“Promise.all results:”, results);
})
.catch(error => {
console.error(“Promise.all error:”, error);
});
// race – 第一个完成的Promise
Promise.race([promise1, promise2])
.then(result => {
console.log(“Promise.race result:”, result);
})
.catch(error => {
console.error(“Promise.race error:”, error);
});
10. JavaScript开发最佳实践
JavaScript开发最佳实践包括代码规范、性能优化、安全性等多个方面。
# 1. 代码规范
– 遵循ESLint规则
– 使用一致的缩进(2或4个空格)
– 使用有意义的变量和函数命名
– 避免使用var,使用let和const
– 使用箭头函数简化代码
– 使用模板字符串代替字符串拼接
# 2. 性能优化
– 避免频繁DOM操作
– 使用事件委托
– 避免使用eval()
– 合理使用缓存
– 优化循环
– 使用requestAnimationFrame进行动画
# 3. 安全性
– 防止XSS攻击
– 防止CSRF攻击
– 避免使用innerHTML
– 验证用户输入
– 使用HTTPS
# 4. 模块化
– 使用ES6模块
– 使用import和export
– 合理组织代码结构
– 避免全局变量污染
# 5. 工具和框架
– 使用包管理器(npm/yarn)
– 使用构建工具(Webpack/Rollup)
– 使用Babel转译ES6+代码
– 考虑使用框架(React/Vue/Angular)
– 使用TypeScript增加类型安全性
# 6. 代码示例
// 好的实践示例
// 使用const和let
const PI = 3.14159;
let count = 0;
// 使用箭头函数
const sum = (a, b) => a + b;
// 使用模板字符串
const name = “Alice”;
const greeting = `Hello, ${name}!`;
// 使用解构赋值
const person = { name: “Bob”, age: 30 };
const { name: personName, age } = person;
// 使用展开运算符
const arr1 = [1, 2, 3];
const arr2 = […arr1, 4, 5];
// 使用async/await
async function fetchData() {
try {
const response = await fetch(“https://api.fgedu.net.cn/data”);
const data = await response.json();
return data;
} catch (error) {
console.error(“Error fetching data:”, error);
throw error;
}
}
// 使用Promise.all处理并行请求
async function fetchMultipleData() {
try {
const [data1, data2] = await Promise.all([
fetch(“https://api.fgedu.net.cn/data1”).then(res => res.json()),
fetch(“https://api.fgedu.net.cn/data2”).then(res => res.json())
]);
return { data1, data2 };
} catch (error) {
console.error(“Error fetching data:”, error);
throw error;
}
}
author:www.itpux.com
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
