下面的代碼會爲String增長一個trim()方法,代碼以下:javascript
- if (!String.prototype.trim) {
- String.prototype.trim=function() {
- return this.replace(/^\s+|\s+$/g, '');
- };
- }
-
-
- var str = " some string ";
- str.trim();
-
18 去掉Javscript數組中的重複元素java
下面的代碼能夠去掉Javascript數組中的重複元素,以下:數組
- 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);
- //輸出的 uniquefruits ['apple', 'orange', 'peach', 'strawberry'];
下面的代碼中,能夠實現檢查某個字符串中是否包含其餘字符串。代碼以下:瀏覽器
- 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);
- };
- }
在上面的代碼中重寫了indexOf方法並定義了contains方法,使用的方法以下:session
- var hay = "a quick brown fox jumps over lazy dog";
- var needle = "jumps";
- alert(hay.contains(needle));
16 截取指定位數的小數app
若是要截取小數後的指定位數,可使用toFixed方法,好比:dom
- var num = 2.443242342;
- alert(num.toFixed(2));
- 而使用toPrecision(x)則提供指定位數的精度,這裏的x是所有的位數,如:
- num = 500.2349;
- result = num.toPrecision(4);
14 在兩個不一樣的Listbox中移動項目ui
若是在兩個不一樣的Listbox中,常常須要在左邊的一個Listbox中移動項目到另一個Listbox中去,下面是相關代碼:this
- 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); //Standard
- src.remove(count, null);
- }catch(error) {
- dest.add(newOption); // IE only
- src.remove(count);
- }
- count--;
- }
- }
- }
- //..
- //..
-
- listbox_moveacross('countryList', 'selectedCountryList');
13 在Listbox中項目的上下移動spa
下面的代碼,給出了在一個listbox中如何上下移動項目
- unction 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 = -1;
- if(direction == 'up')
- increment = -1;
- else
- increment = 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'); //move up the selected option
- listbox_move('countryList', 'down'); //move down the selected option
8 檢查是否按了回退鍵
一樣,能夠檢查用戶是否按了回退鍵,代碼以下:
- window.onbeforeunload = function() {
- return "You work will be lost.";
- };
9 檢查表單數據是否改變
有的時候,須要檢查用戶是否修改了一個表單中的內容,則可使用下面的技巧,其中若是修改了表單的內容則返回true,沒修改表單的內容則返回false。代碼以下:
- 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"])) {
- // IE 和 Firefox
- if (e) {
- e.returnValue = "You have unsaved changes.";
- }
- // Safari瀏覽器
- return "You have unsaved changes.";
- }
- };
10 徹底禁止使用後退鍵
下面的技巧放在頁面中,則能夠防止用戶點後退鍵,這在一些狀況下是須要的。代碼以下:
- <SCRIPT type="text/javascript">
- window.history.forward();
- function noBack() { window.history.forward(); }
- </SCRIPT>
- </HEAD>
- <BODY onload="noBack();"
- onpageshow="if (event.persisted) noBack();" onunload="">
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 Listbox中的全選和非全選
若是對於指定的listbox,下面的方法能夠根據用戶的須要,傳入true或false,分別表明是全選listbox中的全部項目仍是非全選全部項目,代碼以下:
- function listboxSelectDeselect(listID, isSelect) {
- var listbox = document.getElementById(listID);
- for(var count=0; count < listbox.options.length; count++) {
- listbox.options[count].selected = isSelect;
- }
- }
1 Javascript數組轉換爲CSV格式
-
首先考慮以下的應用場景,有一個Javscript的字符型(或者數值型)數組,如今須要轉換爲以逗號分割的CSV格式文件。則咱們可使用以下的小技巧,代碼以下:
- var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
- var str = fruits.valueOf();
輸出:apple,peaches,oranges,mangoes
其中,valueOf()方法會將Javascript數組轉變爲逗號隔開的字符串。要注意的是,若是想不使用逗號分割,好比用|號分割,則請使用join方法,以下:
- var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
- var str = fruits.join("|");
輸出: apple|peaches|oranges|mangoes
2 將CSV格式從新轉換回Javscript數組
那麼如何將一個CSV格式的字符串轉變回Javascript數組呢?可使用split()方法,就可使用任何指定的字符去分隔,代碼以下:
- var str = "apple, peaches, oranges, mangoes";
- var fruitsArray = str.split(",");
輸出 fruitsArray[0]: apple
3 根據索引移除數組中的某個元素
假如須要從Javascript數組中移除某個元素,可使用splice方法,該方法將根據傳入參數n,移除數組中移除第n個元素(Javascript數組中從第0位開始計算)。
- function removeByIndex(arr, index) {
- arr.splice(index, 1);
- }
- test = new Array();
- test[0] = 'Apple';
- test[1] = 'Ball';
- test[2] = 'Cat';
- test[3] = 'Dog';
- alert("Array before removing elements: "+test);
- removeByIndex(test, 2);
- alert("Array after removing elements: "+test);
則最後輸出的爲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");
-
- //somearray 將會有的元素是 "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;
- }
- }
- }
- //..
- var somearray = ["mon", "tue", "wed", "thur"]
- somearray.removeByValue("tue");
5 經過字符串指定的方式動態調用某個方法
有的時候,須要在運行時,動態調用某個已經存在的方法,併爲其傳入參數。這個如何實現呢?下面的代碼能夠:
- var strFun = "someFunction"; //someFunction 爲已經定義的方法名
- var strParam = "this is the parameter"; //要傳入方法的參數
- var fn = window[strFun];
-
- //調用方法傳入參數
- fn(strParam);
6 產生1到N的隨機數
- var random = Math.floor(Math.random() * N + 1);
-
- //產生1到10之間的隨機數
- var random = Math.floor(Math.random() * 10 + 1);
-
- //產生1到100之間的隨機數
- var random = Math.floor(Math.random() * 100 + 1);
7 捕捉瀏覽器關閉的事件
咱們常常但願在用戶關閉瀏覽器的時候,提示用戶要保存還沒有保存的東西,則下面的這個Javascript技巧是十分有用的,代碼以下:
- <script language="javascript">
- function fnUnloadHandler() {
-
- alert("Unload event.. Do something to invalidate users session..");
- }
- </script>
- <body onbeforeunload="fnUnloadHandler()">
- ………
- </body>
就是編寫onbeforeunload()事件的代碼便可