您好,登录后才能下订单哦!
JavaScript中的数据类型分为两大类:原始类型和对象类型。
原始类型:
number
:数字类型,包括整数和浮点数。string
:字符串类型。boolean
:布尔类型,值为true
或false
。null
:表示空值。undefined
:表示未定义的值。symbol
:ES6引入的唯一标识符。对象类型:
object
:对象类型,包括数组、函数、日期等。JavaScript中有三种声明变量的方式:
var
:函数作用域,存在变量提升。let
:块级作用域,不存在变量提升。const
:块级作用域,声明常量,值不可变。JavaScript支持多种运算符:
+
, -
, *
, /
, %
, **
(幂运算)。==
, ===
, !=
, !==
, >
, <
, >=
, <=
。&&
, ||
, !
。=
, +=
, -=
, *=
, /=
, %=
。&
, |
, ^
, ~
, <<
, >>
, >>>
。? :
。JavaScript中的控制结构包括:
条件语句:
if...else
switch...case
循环语句:
for
while
do...while
for...in
for...of
跳转语句:
break
continue
return
throw
JavaScript中的函数是一等公民,可以作为参数传递、返回值、赋值给变量等。
函数声明:
function add(a, b) {
return a + b;
}
函数表达式:
const add = function(a, b) {
return a + b;
};
箭头函数:
const add = (a, b) => a + b;
立即执行函数表达式(IIFE):
(function() {
console.log('IIFE');
})();
JavaScript中的对象是键值对的集合。
对象字面量:
const person = {
name: 'John',
age: 30,
greet: function() {
console.log('Hello');
}
};
构造函数:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log('Hello');
};
}
const person = new Person('John', 30);
原型链:
Person.prototype.greet = function() {
console.log('Hello');
};
JavaScript中的数组是动态的,可以包含不同类型的元素。
数组字面量:
const arr = [1, 2, 3];
数组方法:
push
, pop
, shift
, unshift
slice
, splice
map
, filter
, reduce
forEach
, find
, findIndex
sort
, reverse
concat
, join
JavaScript中的字符串是不可变的。
字符串字面量:
const str = 'Hello';
字符串方法:
charAt
, charCodeAt
indexOf
, lastIndexOf
slice
, substring
, substr
toLowerCase
, toUpperCase
trim
, replace
split
, concat
JavaScript中的日期和时间通过Date
对象处理。
创建日期对象:
const now = new Date();
日期方法:
getFullYear
, getMonth
, getDate
getHours
, getMinutes
, getSeconds
getTime
, setTime
toISOString
, toLocaleString
JavaScript中的正则表达式用于匹配字符串。
创建正则表达式:
const regex = /pattern/flags;
正则表达式方法:
test
, exec
match
, search
replace
, split
JavaScript中的错误处理通过try...catch
语句实现。
try {
// 可能会抛出错误的代码
} catch (error) {
// 处理错误
} finally {
// 无论是否抛出错误都会执行的代码
}
JavaScript中的JSON用于数据交换。
JSON.stringify
:将对象转换为JSON字符串。JSON.parse
:将JSON字符串转换为对象。JavaScript中的Promise用于处理异步操作。
创建Promise:
const promise = new Promise((resolve, reject) => {
// 异步操作
if (success) {
resolve(result);
} else {
reject(error);
}
});
Promise方法:
then
, catch
, finally
Promise.all
, Promise.race
JavaScript中的异步编程通过回调函数、Promise、async/await实现。
回调函数:
function fetchData(callback) {
setTimeout(() => {
callback('Data');
}, 1000);
}
async/await:
async function fetchData() {
const response = await fetch('url');
const data = await response.json();
return data;
}
JavaScript中的模块化通过import
和export
实现。
导出模块:
export const add = (a, b) => a + b;
导入模块:
import { add } from './module';
ES6及之后的版本引入了许多新特性:
DOM(文档对象模型)是HTML和XML文档的编程接口。
JavaScript提供了多种选择元素的方法:
getElementById:
const element = document.getElementById('id');
getElementsByClassName:
const elements = document.getElementsByClassName('class');
getElementsByTagName:
const elements = document.getElementsByTagName('tag');
querySelector:
const element = document.querySelector('selector');
querySelectorAll:
const elements = document.querySelectorAll('selector');
JavaScript可以操作元素的属性、样式、内容等。
修改属性:
element.setAttribute('attribute', 'value');
element.getAttribute('attribute');
修改样式:
element.style.property = 'value';
修改内容:
element.innerHTML = 'content';
element.textContent = 'content';
创建元素:
const newElement = document.createElement('tag');
document.body.appendChild(newElement);
删除元素:
element.remove();
JavaScript可以通过事件处理用户交互。
添加事件监听器:
element.addEventListener('event', handler);
移除事件监听器:
element.removeEventListener('event', handler);
常见事件:
click
, dblclick
mouseover
, mouseout
keydown
, keyup
focus
, blur
submit
, change
JavaScript可以操作表单元素。
获取表单元素:
const form = document.forms['formName'];
const input = form.elements['inputName'];
表单验证:
form.addEventListener('submit', function(event) {
if (!input.value) {
event.preventDefault();
alert('Input is required');
}
});
AJAX(异步JavaScript和XML)用于在不重新加载页面的情况下与服务器通信。
XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'url', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
Fetch API:
fetch('url')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
跨域请求需要处理CORS(跨域资源共享)。
CORS:
fetch('url', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
mode: 'cors'
});
JSONP:
function handleResponse(data) {
console.log(data);
}
const script = document.createElement('script');
script.src = 'url?callback=handleResponse';
document.body.appendChild(script);
BOM(浏览器对象模型)提供了与浏览器窗口交互的对象。
window.location
:当前页面的URL。window.navigator
:浏览器信息。window.history
:浏览历史。window.screen
:屏幕信息。window.document
:当前页面的文档对象。浏览器提供了多种存储方式:
Cookie:
document.cookie = 'name=value; expires=date; path=path';
LocalStorage:
localStorage.setItem('key', 'value');
localStorage.getItem('key');
SessionStorage:
sessionStorage.setItem('key', 'value');
sessionStorage.getItem('key');
IndexedDB:
const request = indexedDB.open('database', 1);
request.onupgradeneeded = function(event) {
const db = event.target.result;
const store = db.createObjectStore('store', { keyPath: 'id' });
};
浏览器性能优化包括:
减少HTTP请求:
压缩资源:
缓存:
延迟加载:
减少重绘和重排:
transform
和opacity
浏览器兼容性需要考虑不同浏览器的差异。
Polyfill:
if (!Array.prototype.includes) {
Array.prototype.includes = function(element) {
return this.indexOf(element) !== -1;
};
}
特性检测:
if ('fetch' in window) {
// 使用Fetch API
} else {
// 使用XMLHttpRequest
}
单例模式确保一个类只有一个实例。
const Singleton = (function() {
let instance;
function createInstance() {
return new Object('I am the instance');
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
工厂模式用于创建对象。
function createProduct(type) {
if (type === 'A') {
return new ProductA();
} else if (type === 'B') {
return new ProductB();
}
}
观察者模式定义对象间的一对多依赖关系。
class Subject {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
notify(data) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
update(data) {
console.log(data);
}
}
发布-订阅
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。