萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

21 個實用 JavaScript 技巧大全:從數組操作到瀏覽器事件

陣列操作篇

1. 陣列轉 CSV 字符串

const fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
const csv = fruits.valueOf(); // "apple,peaches,oranges,mangoes"
// 自定義分隔符
const custom = fruits.join('|'); // "apple|peaches|oranges|mangoes"

2. CSV 轉回陣列

const str = "apple, peaches, oranges, mangoes";
const arr = str.split(","); // ["apple", " peaches", " oranges", " mangoes"]
// 建議配合 map 去除空格
const clean = str.split(",").map(s => s.trim());

3. 按索引移除元素

function removeByIndex(arr, index) {
  arr.splice(index, 1);
}
const test = ['Apple', 'Ball', 'Cat', 'Dog'];
removeByIndex(test, 2); // 移除 'Cat',結果: ['Apple', 'Ball', 'Dog']

4. 按值移除元素(兩種寫法)

// 普通函數
function removeByValue(arr, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === val) {
      arr.splice(i, 1);
      break;
    }
  }
}

// 原型擴展(慎用,污染原型鏈)
Array.prototype.removeByValue = function(val) {
  const idx = this.indexOf(val);
  if (idx !== -1) this.splice(idx, 1);
};

動態調用篇

5. 字符串動態調用函數

const strFun = "someFunction";
const strParam = "this is the parameter";
const fn = window[strFun];
if (typeof fn === 'function') fn(strParam);
// ES6 更安全
const fn = (window[strFun] || Function.prototype).bind(window);
fn(strParam);

6. 生成範圍隨機數

// 1 到 N
const random = Math.floor(Math.random() * N) + 1;
// 示例
const r10 = Math.floor(Math.random() * 10) + 1;   // 1-10
const r100 = Math.floor(Math.random() * 100) + 1; // 1-100

瀏覽器事件篇

7. 捕獲頁面卸載事件

window.addEventListener('beforeunload', (e) => {
  e.preventDefault();
  e.returnValue = '您有未保存的內容,確定離開?';
  return e.returnValue;
});

8. 檢測後退鍵(歷史導航)

window.onbeforeunload = () => '您的操作將不會被保存。';

9. 表單髒數據檢測

function isFormDirty(form) {
  return Array.from(form.elements).some(el => {
    if (el.type === 'checkbox' || el.type === 'radio') 
      return el.checked !== el.defaultChecked;
    return el.value !== el.defaultValue;
  });
}

更多實用片段

  • 深拷貝:JSON.parse(JSON.stringify(obj))(不含函數/RegExp/Date)
  • 防抖:const debounce = (fn, ms) => { let t; return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); }; }
  • 節流:const throttle = (fn, ms) => { let last = 0; return (...args) => { const now = Date.now(); if (now - last >= ms) { last = now; fn(...args); } }; }
  • 唯一 ID:() => Math.random().toString(36).substr(2, 9)
  • 扁平化陣列:arr.flat(Infinity) (ES2019)
  • 對象屬性重命名:const { oldName: newName, ...rest } = obj;

使用建議

這些技巧適用於快速原型開發、算法題、工具函數庫構建。生產環境複雜邏輯請使用成熟庫,注意代碼可讀性與維護性。

copyright © 萬盛學電腦網 all rights reserved