21个值得收藏的Javascript技巧

十度 javaScript 2016年01月20日 收藏

在本文中列出了21个值得收藏的Javascript技巧,在实际工作中,如果能适当运用,则大大提高工作效率。

 

  1  Javascript数组转换为CSV格式

  首先考虑如下的应用场景,有一个Javscript的字符型(或者数值型)数组,现在需要转换为以逗号分割的CSV格式文件。则我们可以使用如下的小技巧,代码如下:

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

  输出:apple,peaches,oranges,mangoes

  其中,valueOf()方法会将Javascript数组转变为逗号隔开的字符串。要注意的是,如果想不使用逗号分割,比如用|号分割,则请使用join方法,如下:


  1. var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
  2. var str = fruits.join("|")

  输出: apple|peaches|oranges|mangoes

  2 将CSV格式重新转换回Javscript数组

  那么如何将一个CSV格式的字符串转变回Javascript数组呢?可以使用split()方法,就可以使用任何指定的字符去分隔,代码如下:


  1. var str = "apple, peaches, oranges, mangoes";
  2. var fruitsArray = str.split(",")

  输出 fruitsArray[0]: apple

  3 根据索引移除数组中的某个元素

  假如需要从Javascript数组中移除某个元素,可以使用splice方法,该方法将根据传入参数n,移除数组中移除第n个元素(Javascript数组中从第0位开始计算)。


  1. function removeByIndex(arr, index) {
  2.     arr.splice(index, 1);
  3. }
  4. test = new Array();
  5. test[0] = 'Apple';
  6. test[1] = 'Ball';
  7. test[2] = 'Cat';
  8. test[3] = 'Dog';
  9. alert("Array before removing elements: "+test);
  10. removeByIndex(test, 2);
  11. alert("Array after removing elements: "+test)

  则最后输出的为Apple,Ball,Dog

  4 根据元素的值移除数组元素中的值

  下面这个技巧是很实用的,是根据给定的值去删除数组中的元素,代码如下:


  1. function removeByValue(arr, val) {
  2.     for(var i=0; i<arr.length; i++) {
  3.         if(arr[i] == val) {
  4.             arr.splice(i, 1);
  5.             break;
  6.         }
  7.     }
  8. }
  9. var somearray = ["mon", "tue", "wed", "thur"]
  10. removeByValue(somearray, "tue");
  11. //somearray 将会有的元素是 "mon", "wed", "thur

  当然,更好的方式是使用prototype的方法去实现,如下代码:


  1. Array.prototype.removeByValue = function(val) {
  2.     for(var i=0; i<this.length; i++) {
  3.         if(this[i] == val) {
  4.             this.splice(i, 1);
  5.             break;
  6.         }
  7.     }
  8. }
  9. //..
  10. var somearray = ["mon", "tue", "wed", "thur"]
  11. somearray.removeByValue("tue")

  5 通过字符串指定的方式动态调用某个方法

  有的时候,需要在运行时,动态调用某个已经存在的方法,并为其传入参数。这个如何实现呢?下面的代码可以:


  1. var strFun = "someFunction"; //someFunction 为已经定义的方法名
  2. var strParam = "this is the parameter"; //要传入方法的参数
  3. var fn = window[strFun];
  4.  
  5. //调用方法传入参数
  6. fn(strParam)

  6 产生1到N的随机数


  1. var random = Math.floor(Math.random() * N + 1);
  2.  
  3. //产生1到10之间的随机数
  4. var random = Math.floor(Math.random() * 10 + 1);
  5.  
  6. //产生1到100之间的随机数
  7. var random = Math.floor(Math.random() * 100 + 1)

  7 捕捉浏览器关闭的事件

  我们经常希望在用户关闭浏览器的时候,提示用户要保存尚未保存的东西,则下面的这个Javascript技巧是十分有用的,代码如下:


  1. <script language="javascript">
  2. function fnUnloadHandler() {
  3.  
  4.        alert("Unload event.. Do something to invalidate users session..");
  5. }
  6. </script>
  7. <body onbeforeunload="fnUnloadHandler()">
  8. ………
  9. </body

  就是编写onbeforeunload()事件的代码即可

  8  检查是否按了回退键

  同样,可以检查用户是否按了回退键,代码如下:


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

  9  检查表单数据是否改变

  有的时候,需要检查用户是否修改了一个表单中的内容,则可以使用下面的技巧,其中如果修改了表单的内容则返回true,没修改表单的内容则返回false。代码如下:


  1. function formIsDirty(form) {
  2.   for (var i = 0; i < form.elements.length; i++) {
  3.     var element = form.elements[i];
  4.     var type = element.type;
  5.     if (type == "checkbox" || type == "radio") {
  6.       if (element.checked != element.defaultChecked) {
  7.         return true;
  8.       }
  9.     }
  10.     else if (type == "hidden" || type == "password" ||
  11.              type == "text" || type == "textarea") {
  12.       if (element.value != element.defaultValue) {
  13.         return true;
  14.       }
  15.     }
  16.     else if (type == "select-one" || type == "select-multiple") {
  17.       for (var j = 0; j < element.options.length; j++) {
  18.         if (element.options[j].selected !=
  19.             element.options[j].defaultSelected) {
  20.           return true;
  21.         }
  22.       }
  23.     }
  24.   }
  25.   return false;
  26. }
  27.  
  28. window.onbeforeunload = function(e) {
  29.   e = e || window.event; 
  30.   if (formIsDirty(document.forms["someForm"])) {
  31.     // IE 和 Firefox
  32.     if (e) {
  33.       e.returnValue = "You have unsaved changes.";
  34.     }
  35.     // Safari 浏览器
  36.     return "You have unsaved changes.";
  37.   }
  38. }

  10  完全禁止使用后退键

  下面的技巧放在页面中,则可以防止用户点后退键,这在一些情况下是需要的。代码如下:


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

  11 删除用户多选框中选择的项目

  下面提供的技巧,是当用户在下拉框多选项目的时候,当点删除的时候,可以一次删除它们,代码如下:


  1. function selectBoxRemove(sourceID) {
  2.   
  3.  
  4.     //获得listbox的id
  5.     var src = document.getElementById(sourceID);
  6.    
  7.  
  8.     //循环listbox
  9.     for(var count= src.options.length-1; count >= 0; count--) {
  10.   
  11.  
  12.          //如果找到要删除的选项,则删除
  13.         if(src.options[count].selected == true) {
  14.    
  15.  
  16.                 try {
  17.                          src.remove(count, null);
  18.                           
  19.  
  20.                  } catch(error) {
  21.                           
  22.  
  23.                          src.remove(count);
  24.                 }
  25.         }
  26.     }

  12  Listbox中的全选和非全选

  如果对于指定的listbox,下面的方法可以根据用户的需要,传入true或false,分别代表是全选listbox中的所有项目还是非全选所有项目,代码如下:


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

  13 在Listbox中项目的上下移动

  下面的代码,给出了在一个listbox中如何上下移动项目


  1. function listbox_move(listID, direction) {
  2.   
  3.  
  4.     var listbox = document.getElementById(listID);
  5.     var selIndex = listbox.selectedIndex;
  6.   
  7.  
  8.     if(-1 == selIndex) {
  9.         alert("Please select an option to move.");
  10.         return;
  11.     }
  12.   
  13.  
  14.     var increment = -1;
  15.     if(direction == 'up')
  16.         increment = -1;
  17.     else
  18.         increment = 1;
  19.   
  20.  
  21.     if((selIndex + increment) < 0 ||
  22.         (selIndex + increment) > (listbox.options.length-1)) {
  23.         return;
  24.     }
  25.   
  26.  
  27.     var selValue = listbox.options[selIndex].value;
  28.     var selText = listbox.options[selIndex].text;
  29.     listbox.options[selIndex].value = listbox.options[selIndex + increment].value
  30.     listbox.options[selIndex].text = listbox.options[selIndex + increment].text
  31.   
  32.  
  33.     listbox.options[selIndex + increment].value = selValue;
  34.     listbox.options[selIndex + increment].text = selText;
  35.   
  36.  
  37.     listbox.selectedIndex = selIndex + increment;
  38. }
  39. //..
  40. //..
  41.  
  42.  
  43. listbox_move('countryList', 'up'); //move up the selected option
  44. listbox_move('countryList', 'down'); //move down the selected optio

  14 在两个不同的Listbox中移动项目

  如果在两个不同的Listbox中,经常需要在左边的一个Listbox中移动项目到另外一个Listbox中去,下面是相关代码:


  1. function listbox_moveacross(sourceID, destID) {
  2.     var src = document.getElementById(sourceID);
  3.     var dest = document.getElementById(destID);
  4.   
  5.  
  6.     for(var count=0; count < src.options.length; count++) {
  7.   
  8.  
  9.         if(src.options[count].selected == true) {
  10.                 var option = src.options[count];
  11.   
  12.  
  13.                 var newOption = document.createElement("option");
  14.                 newOption.value = option.value;
  15.                 newOption.text = option.text;
  16.                 newOption.selected = true;
  17.                 try {
  18.                          dest.add(newOption, null); //Standard
  19.                          src.remove(count, null);
  20.                  }catch(error) {
  21.                          dest.add(newOption); // IE only
  22.                          src.remove(count);
  23.                  }
  24.                 count--;
  25.         }
  26.     }
  27. }
  28. //..
  29. //..
  30. listbox_moveacross('countryList', 'selectedCountryList')

  15 快速初始化Javscript数组

  下面的方法,给出了一种快速初始化Javscript数组的方法,代码如下:


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

  使用的是数组的push方法

  16 截取指定位数的小数

  如果要截取小数后的指定位数,可以使用toFixed方法,比如:

  1. var num = 2.443242342;
  2. alert(num.toFixed(2))

  而使用toPrecision(x)则提供指定位数的精度,这里的x是全部的位数,如:


  1. num = 500.2349;
  2. result = num.toPrecision(4); //输出500.

  17 检查字符串中是否包含其他字符串

  下面的代码中,可以实现检查某个字符串中是否包含其他字符串。代码如下:


  1. if (!Array.prototype.indexOf) {
  2.     Array.prototype.indexOf = function(obj, start) {
  3.          for (var i = (start || 0), j = this.length; i < j; i++) {
  4.              if (this[i] === obj) { return i; }
  5.          }
  6.          return -1;
  7.     }
  8. }
  9.  
  10.  
  11. if (!String.prototype.contains) {
  12.     String.prototype.contains = function (arg) {
  13.         return !!~this.indexOf(arg);
  14.     };
  15. }

  在上面的代码中重写了indexOf方法并定义了contains方法,使用的方法如下:


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

  18  去掉Javscript数组中的重复元素

  下面的代码可以去掉Javascript数组中的重复元素,如下:


  1. function removeDuplicates(arr) {
  2.     var temp = {};
  3.     for (var i = 0; i < arr.length; i++)
  4.         temp[arr[i]] = true;
  5.  
  6.  
  7.     var r = [];
  8.     for (var k in temp)
  9.         r.push(k);
  10.     return r;
  11. }
  12.  
  13. //用法
  14. var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
  15. var uniquefruits = removeDuplicates(fruits);
  16. //输出 uniquefruits ['apple', 'orange', 'peach', 'strawberry'];

  19  去掉String中的多余空格

  下面的代码会为String增加一个trim()方法,代码如下:


  1. if (!String.prototype.trim) {
  2.    String.prototype.trim=function() {
  3.     return this.replace(/^\s+|\s+$/g, '');
  4.    };
  5. }
  6.  
  7.  
  8. //用法
  9. var str = "  some string    ";
  10. str.trim();
  11. //输出 str = "some string"

  20 Javascript中的重定向

  在Javascript中,可以实现重定向,方法如下:

  1. window.location.href = <a href="http://viralpatel.net" class="">http://viralpatel.net</a>;


  21 对URL进行编码

  有的时候,需要对URL中的传递的进行编码,方法如下:

  1. var myOtherUrl =
  2.        "http://shouce.ren/index.html?url=" + encodeURIComponent(myUrl)