1 Javascript數(shù)組轉(zhuǎn)換為CSV格式
首先考慮如下的應(yīng)用場(chǎng)景,有一個(gè)Javscript的字符型(或者數(shù)值型)數(shù)組,現(xiàn)在需要轉(zhuǎn)換為以逗號(hào)分割的CSV格式文件。則我們可以使用如下的小技巧,代碼如下:
- var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
- var str = fruits.valueOf();
輸出:apple,peaches,oranges,mangoes
其中,valueOf()方法會(huì)將Javascript數(shù)組轉(zhuǎn)變?yōu)槎禾?hào)隔開的字符串。要注意的是,如果想不使用逗號(hào)分割,比如用|號(hào)分割,則請(qǐng)使用join方法,如下:
- var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
- var str = fruits.join("|");
輸出: apple|peaches|oranges|mangoes
2 將CSV格式重新轉(zhuǎn)換回Javscript數(shù)組
那么如何將一個(gè)CSV格式的字符串轉(zhuǎn)變回Javascript數(shù)組呢?可以使用split()方法,就可以使用任何指定的字符去分隔,代碼如下:
- var str = "apple, peaches, oranges, mangoes";
- var fruitsArray = str.split(",");
輸出 fruitsArray[0]: apple
3 根據(jù)索引移除數(shù)組中的某個(gè)元素
假如需要從Javascript數(shù)組中移除某個(gè)元素,可以使用splice方法,該方法將根據(jù)傳入?yún)?shù)n,移除數(shù)組中移除第n個(gè)元素(Javascript數(shù)組中從第0位開始計(jì)算)。
- 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 根據(jù)元素的值移除數(shù)組元素中的值
下面這個(gè)技巧是很實(shí)用的,是根據(jù)給定的值去刪除數(shù)組中的元素,代碼如下:
- 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");
-
-
當(dāng)然,更好的方式是使用prototype的方法去實(shí)現(xiàn),如下代碼:
- 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 通過(guò)字符串指定的方式動(dòng)態(tài)調(diào)用某個(gè)方法
有的時(shí)候,需要在運(yùn)行時(shí),動(dòng)態(tài)調(diào)用某個(gè)已經(jīng)存在的方法,并為其傳入?yún)?shù)。這個(gè)如何實(shí)現(xiàn)呢?下面的代碼可以:
- var strFun = "someFunction";
- var strParam = "this is the parameter";
- var fn = window[strFun];
-
-
- fn(strParam);
6 產(chǎn)生1到N的隨機(jī)數(shù)
- var random = Math.floor(Math.random() * N + 1);
-
-
- var random = Math.floor(Math.random() * 10 + 1);
-
-
- var random = Math.floor(Math.random() * 100 + 1);
7 捕捉瀏覽器關(guān)閉的事件
我們經(jīng)常希望在用戶關(guān)閉瀏覽器的時(shí)候,提示用戶要保存尚未保存的東西,則下面的這個(gè)Javascript技巧是十分有用的,代碼如下:
- <script language="javascript">
- function fnUnloadHandler() {
-
- alert("Unload event.. Do something to invalidate users session..");
- }
- </script>
- <body onbeforeunload="fnUnloadHandler()">
- ………
- </body>
就是編寫onbeforeunload()事件的代碼即可
8 檢查是否按了回退鍵
同樣,可以檢查用戶是否按了回退鍵,代碼如下:
- window.onbeforeunload = function() {
- return "You work will be lost.";
- };
9 檢查表單數(shù)據(jù)是否改變
有的時(shí)候,需要檢查用戶是否修改了一個(gè)表單中的內(nèi)容,則可以使用下面的技巧,其中如果修改了表單的內(nèi)容則返回true,沒修改表單的內(nèi)容則返回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"])) {
-
- if (e) {
- e.returnValue = "You have unsaved changes.";
- }
-
- return "You have unsaved changes.";
- }
- };
10 完全禁止使用后退鍵
下面的技巧放在頁(yè)面中,則可以防止用戶點(diǎn)后退鍵,這在一些情況下是需要的。代碼如下:
- <SCRIPT type="text/javascript">
- window.history.forward();
- function noBack() { window.history.forward(); }
- </SCRIPT>
- </HEAD>
- <BODY onload="noBack();"
- onpageshow="if (event.persisted) noBack();" onunload="">
11 刪除用戶多選框中選擇的項(xiàng)目
下面提供的技巧,是當(dāng)用戶在下拉框多選項(xiàng)目的時(shí)候,當(dāng)點(diǎn)刪除的時(shí)候,可以一次刪除它們,代碼如下:
- 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中的全選和非全選
如果對(duì)于指定的listbox,下面的方法可以根據(jù)用戶的需要,傳入true或false,分別代表是全選listbox中的所有項(xiàng)目還是非全選所有項(xiàng)目,代碼如下:
- function listboxSelectDeselect(listID, isSelect) {
- var listbox = document.getElementById(listID);
- for(var count=0; count < listbox.options.length; count++) {
- listbox.options[count].selected = isSelect;
- }
- }
13 在Listbox中項(xiàng)目的上下移動(dòng)
下面的代碼,給出了在一個(gè)listbox中如何上下移動(dòng)項(xiàng)目
- 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');
- listbox_move('countryList', 'down');
14 在兩個(gè)不同的Listbox中移動(dòng)項(xiàng)目
如果在兩個(gè)不同的Listbox中,經(jīng)常需要在左邊的一個(gè)Listbox中移動(dòng)項(xiàng)目到另外一個(gè)Listbox中去,下面是相關(guān)代碼:
- 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);
- src.remove(count);
- }
- count--;
- }
- }
- }
-
-
-
- listbox_moveacross('countryList', 'selectedCountryList');
15 快速初始化Javscript數(shù)組
下面的方法,給出了一種快速初始化Javscript數(shù)組的方法,代碼如下:
- var numbers = [];
- for(var i=1; numbers.push(i++)<100;);
-
- 使用的是數(shù)組的push方法
16 截取指定位數(shù)的小數(shù)
如果要截取小數(shù)后的指定位數(shù),可以使用toFixed方法,比如:
- var num = 2.443242342;
- alert(num.toFixed(2));
- 而使用toPrecision(x)則提供指定位數(shù)的精度,這里的x是全部的位數(shù),如:
- num = 500.2349;
- result = num.toPrecision(4);
17 檢查字符串中是否包含其他字符串
下面的代碼中,可以實(shí)現(xiàn)檢查某個(gè)字符串中是否包含其他字符串。代碼如下:
- 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方法,使用的方法如下:
- var hay = "a quick brown fox jumps over lazy dog";
- var needle = "jumps";
- alert(hay.contains(needle));
18 去掉Javscript數(shù)組中的重復(fù)元素
下面的代碼可以去掉Javascript數(shù)組中的重復(fù)元素,如下:
- 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);
-
19 去掉String中的多余空格
下面的代碼會(huì)為String增加一個(gè)trim()方法,代碼如下:
- if (!String.prototype.trim) {
- String.prototype.trim=function() {
- return this.replace(/^\s+|\s+$/g, '');
- };
- }
-
-
- var str = " some string ";
- str.trim();
-
20 Javascript中的重定向
在Javascript中,可以實(shí)現(xiàn)重定向,方法如下:
- window.location.href = "http://viralpatel.net";
21 對(duì)URL進(jìn)行編碼
有的時(shí)候,需要對(duì)URL中的傳遞的進(jìn)行編碼,方法如下:
- var myOtherUrl =
- "http://example.com/index.html?url=" + encodeURIComponent(myUrl);