DIV CSS 佈局教程網

21 個值得收藏的 JavaScript 實用技巧
編輯:JavaScript綜合知識     

日常開發中真正省時間的,往往不是框架 API,而是幾個順手的小技巧。以下整理 21 個常見場景與對應寫法,可當成随手查閱的小抄。

一、陣列與字串互轉

1. 陣列轉 CSV

var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
var str = fruits.valueOf();   // apple,peaches,oranges,mangoes

valueOf() 會把陣列攤平成以逗號分隔的字串。若想用其他分隔符,改用 join:

var str = fruits.join('|');   // apple|peaches|oranges|mangoes

2. CSV 字串轉回陣列

var str = "apple, peaches, oranges, mangoes";
var fruitsArray = str.split(',');
console.log(fruitsArray[0]);   // apple

二、陣列元素的移除

3. 依索引移除

function removeByIndex(arr, index) {
  arr.splice(index, 1);
}
var test = ['Apple', 'Ball', 'Cat', 'Dog'];
removeByIndex(test, 2);   // Apple, Ball, Dog

4. 依值移除

function removeByValue(arr, val) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == val) {
      arr.splice(i, 1);
      break;
    }
  }
}
var somearray = ["mon", "tue", "wed", "thur"];
removeByValue(somearray, "tue");   // mon, wed, thur

寫成 prototype 方法呼叫起來更順手:

Array.prototype.removeByValue = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == val) { this.splice(i, 1); break; }
  }
};
["mon", "tue", "wed"].removeByValue("tue");

現代寫法直接用 filter 即可:arr.filter(x => x !== 'tue'),不會改動原陣列,也不需擴充原型。

三、動態呼叫與隨機數

5. 用字串名稱呼叫函式

var strFun = "someFunction";            // 已定義的函式名稱
var strParam = "this is the parameter";
var fn = window[strFun];
fn(strParam);

6. 產生 1 到 N 的隨機整數

var random = Math.floor(Math.random() * N + 1);
Math.floor(Math.random() * 10 + 1);    // 1–10
Math.floor(Math.random() * 100 + 1);   // 1–100

四、頁面卸載與表單狀態

7. 捕捉瀏覽器關閉

<script language="javascript">
function fnUnloadHandler() {
  alert("Unload event.. Do something to invalidate users session..");
}
</script>
<body onbeforeunload="fnUnloadHandler()">
</body>

8. 攔住回退鍵並提醒

window.onbeforeunload = function () {
  return "You work will be lost.";
};

9. 檢查表單是否被修改過

function formIsDirty(form) {
  for (var i = 0; i < form.elements.length; i++) {
    var element = form.elements[i];
    var type = element.type;
    if (type == "checkbox" || type == "radio") {
      if (element.checked != element.defaultChecked) return true;
    } else if (type == "hidden" || type == "password" ||
               type == "text" || type == "textarea") {
      if (element.value != element.defaultValue) return true;
    } else if (type == "select-one" || type == "select-multiple") {
      for (var j = 0; j < element.options.length; j++) {
        if (element.options[j].selected != element.options[j].defaultSelected) return true;
      }
    }
  }
  return false;
}

window.onbeforeunload = function (e) {
  e = e || window.event;
  if (formIsDirty(document.forms["someForm"])) {
    if (e) { e.returnValue = "You have unsaved changes."; }  // IE 與 Firefox
    return "You have unsaved changes.";                      // Safari
  }
};

技巧重點是比對「目前值」與「預設值」,而非只檢查是否為空。

10. 禁用回退鍵

<SCRIPT type="text/javascript">
  window.history.forward();
  function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">

要留意:這種做法會嚴重損害使用者體驗與可親和性,除非是特殊的流程性頁面,否則不建議使用。

五、Select 與 Listbox 操作

11. 批次刪除已勾選項目

function selectBoxRemove(sourceID) {
  var src = document.getElementById(sourceID);
  for (var count = src.options.length - 1; count >= 0; count--) {
    if (src.options[count].selected == true) {
      try { src.remove(count, null); } catch (error) { src.remove(count); }
    }
  }
}

從後往前迴圈是關鍵,避免刪除後索引位移而漏刪。

12. 全選與取消全選

function listboxSelectDeselect(listID, isSelect) {
  var listbox = document.getElementById(listID);
  for (var count = 0; count < listbox.options.length; count++) {
    listbox.options[count].selected = isSelect;
  }
}

13. 項目上下移動

function listbox_move(listID, direction) {
  var listbox = document.getElementById(listID);
  var selIndex = listbox.selectedIndex;

  if (-1 == selIndex) { alert("Please select an option to move."); return; }

  var increment = (direction == 'up') ? -1 : 1;
  if ((selIndex + increment) < 0 ||
      (selIndex + increment) > (listbox.options.length - 1)) { return; }

  var selValue = listbox.options[selIndex].value;
  var selText = listbox.options[selIndex].text;

  listbox.options[selIndex].value = listbox.options[selIndex + increment].value;
  listbox.options[selIndex].text = listbox.options[selIndex + increment].text;
  listbox.options[selIndex + increment].value = selValue;
  listbox.options[selIndex + increment].text = selText;

  listbox.selectedIndex = selIndex + increment;
}
// listbox_move('countryList', 'up');

14. 跨兩個 Listbox 搬移項目

function listbox_moveacross(sourceID, destID) {
  var src = document.getElementById(sourceID);
  var dest = document.getElementById(destID);

  for (var count = 0; count < src.options.length; count++) {
    if (src.options[count].selected == true) {
      var option = src.options[count];
      var newOption = document.createElement("option");
      newOption.value = option.value;
      newOption.text = option.text;
      newOption.selected = true;
      try {
        dest.add(newOption, null);   // 標準寫法
        src.remove(count, null);
      } catch (error) {
        dest.add(newOption);         // 舊 IE
        src.remove(count);
      }
      count--;
    }
  }
}
// listbox_moveacross('countryList', 'selectedCountryList');

六、數值與字串處理

15. 快速初始化陣列

var numbers = [];
for (var i = 1; numbers.push(i++) < 100;);
// numbers = [0,1,2,3 ... 100]

現代寫法更清楚:Array.from({length: 100}, (_, i) => i)。

16. 指定小數位數與精度

var num = 2.443242342;
alert(num.toFixed(2));        // 2.44(回傳字串)

num = 500.2349;
var result = num.toPrecision(4);   // 500.2,x 是「總位數」

兩者差別要記牢:toFixed 指定小數位數,toPrecision 指定有效位數。

17. 檢查字串是否包含子字串

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0), j = this.length; i < j; i++) {
      if (this[i] === obj) { return i; }
    }
    return -1;
  };
}

if (!String.prototype.contains) {
  String.prototype.contains = function (arg) {
    return !!~this.indexOf(arg);
  };
}

var hay = "a quick brown fox jumps over lazy dog";
var needle = "jumps";
alert(hay.contains(needle));

其中 !!~ 是把 -1 之外的值轉為 true 的簡寫。如今直接用 hay.includes('jumps') 就好,不必自己擴充。

18. 陣列去重

function removeDuplicates(arr) {
  var temp = {};
  for (var i = 0; i < arr.length; i++) temp[arr[i]] = true;
  var r = [];
  for (var k in temp) r.push(k);
  return r;
}

var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
// ['apple', 'orange', 'peach', 'strawberry']

注意此法會把值轉成字串鍵名,數字型別會失真;現在一行 [...new Set(arr)] 就能保留型別。

19. 去除字串頭尾空白

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
  };
}

var str = "   some string   ";
str.trim();   // "some string"

ES5 之後原生就有 trim(),實作時直接呼叫即可。

20. 頁面重定向

window.location.href = "https://viralpatel.net";

21. URL 編碼

var myOtherUrl = "https://example.com/index.html?url=" + encodeURIComponent(myUrl);

若要處理整個查詢字串,可用 URLSearchParams 或 encodeURI,兩者適用範圍不同:encodeURIComponent 用於單一參數值,encodeURI 用於完整網址。

寫在最後

這份清單有個共同趨勢:不少技巧是 ES5 時代為了填補標準不足而生的。今天的 JavaScript 已經內建 includes、Set、trim、Array.from、URLSearchParams 等工具,優先使用原生 API 會讓程式碼更短、更不易出錯。真正值得記住的,是背後的思路——例如「從後往前迴圈刪除」與「比對預設值判斷是否修改」——這些觀念不會隨版本過時。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved