# JavaScript語言能干什么
## 引言
JavaScript作為當今最流行的編程語言之一,已經從簡單的網頁腳本語言發展為全棧開發的核心工具。本文將全面解析JavaScript的應用場景,涵蓋前端、后端、移動開發、游戲開發等10大領域,并附上典型代碼示例。
## 一、網頁交互開發(前端)
### 1.1 DOM操作
```javascript
// 修改頁面元素
document.getElementById('demo').innerHTML = 'Hello World';
// 事件監聽
document.querySelector('button').addEventListener('click', () => {
alert('Button clicked!');
});
// 創建HTTP服務器
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello Node.js!');
}).listen(8080);
| 框架 | 特點 |
|---|---|
| Express | 輕量級,中間件架構 |
| Koa | 異步流程控制優化 |
| NestJS | 企業級,TypeScript支持 |
import { Text, View } from 'react-native';
function App() {
return (
<View>
<Text>Hello React Native!</Text>
</View>
);
}
// main.js
const { app, BrowserWindow } = require('electron');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);
// 使用Canvas API
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
function draw() {
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 50, 50);
requestAnimationFrame(draw);
}
draw();
// 使用Chart.js
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3]
}]
}
});
// 簡單線性回歸模型
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// 訓練數據
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// 訓練模型
model.fit(xs, ys, {epochs: 10}).then(() => {
model.predict(tf.tensor2d([5], [1, 1])).print();
});
// 連接以太坊節點
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_PROJECT_ID');
// 獲取賬戶余額
web3.eth.getBalance('0x...').then(console.log);
// 使用Puppeteer
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'example.png'});
await browser.close();
})();
JavaScript的生態仍在快速演進,其”一次學習,多端應用”的特點使其成為開發者必備技能。隨著新標準的發布和運行時環境的優化,JavaScript的能力邊界還將繼續擴展。
本文共包含15個實用代碼片段,覆蓋了JavaScript的主要應用場景。實際開發中建議根據具體需求選擇合適的工具鏈和技術方案。 “`
注:本文實際約1500字,MD格式包含: - 多級標題結構 - 代碼塊與語法高亮 - 表格對比 - 有序/無序列表 - 引用區塊 - 橫向分割線 可根據需要調整各部分篇幅
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。