21个值得收藏的Javascript技巧

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

  1 Javascript数组转换为CSV格式

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

1

2

varfruits = ['apple','peaches','oranges','mangoes'];

varstr = fruits.valueOf();

  输出:apple,peaches,oranges,mangoes

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

1

2

varfruits = ['apple','peaches','oranges','mangoes'];

varstr = fruits.join("|");

  输出: apple|peaches|oranges|mangoes

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

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

1

2

varstr ="apple, peaches, oranges, mangoes";

varfruitsArray = str.split(",");

  输出 fruitsArray[0]: apple

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

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

1

2

3

4

5

6

7

8

9

10

11

functionremoveByIndex(arr, index) {

arr.splice(index, 1);

}

test =newArray();

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 根据元素的值移除数组元素中的值

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

1

2

3

4

5

6

7

8

9

10

11

functionremoveByValue(arr, val) {

for(vari=0; i<arr.length; i++) {

if(arr[i] == val) {

arr.splice(i, 1);

break;

}

}

}

varsomearray = ["mon","tue","wed","thur"]

removeByValue(somearray,"tue");

//somearray 将会有的元素是 "mon", "wed", "thur"

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

1

2

3

4

5

6

7

8

9

10

11

Array.prototype.removeByValue =function(val) {

for(vari=0; i<this.length; i++) {

if(this[i] == val) {

this.splice(i, 1);

break;

}

}

}

//..

varsomearray = ["mon","tue","wed","thur"]

somearray.removeByValue("tue");

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

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

1

2

3

4

5

6

varstrFun ="someFunction";//someFunction 为已经定义的方法名

varstrParam ="this is the parameter";//要传入方法的参数

varfn = window[strFun];

//调用方法传入参数

fn(strParam);

  6 产生1到N的随机数

1

2

3

4

5

6

7

varrandom = Math.floor(Math.random() * N + 1);

//产生1到10之间的随机数

varrandom = Math.floor(Math.random() * 10 + 1);

//产生1到100之间的随机数

varrandom = Math.floor(Math.random() * 100 + 1);

  7 捕捉浏览器关闭的事件

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

1

2

3

4

5

6

7

8

9

<script language="javascript">

functionfnUnloadHandler() {

alert("Unload event.. Do something to invalidate users session..");

}

</script>

<body onbeforeunload="fnUnloadHandler()">

………

</body>

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

  8 检查是否按了回退键

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

1

2

3

window.onbeforeunload =function() {

return"You work will be lost.";

};

  9 检查表单数据是否改变

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

functionformIsDirty(form) {

for(vari = 0; i < form.elements.length; i++) {

varelement = form.elements[i];

vartype = element.type;

if(type =="checkbox"|| type =="radio") {

if(element.checked != element.defaultChecked) {

returntrue;

}

}

elseif(type =="hidden"|| type =="password"||

type =="text"|| type =="textarea") {

if(element.value != element.defaultValue) {

returntrue;

}

}

elseif(type =="select-one"|| type =="select-multiple") {

for(varj = 0; j < element.options.length; j++) {

if(element.options[j].selected !=

element.options[j].defaultSelected) {

returntrue;

}

}

}

}

returnfalse;

}

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 完全禁止使用后退键

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

1

2

3

4

5

6

7

<SCRIPT type="text/javascript">

window.history.forward();

functionnoBack() { window.history.forward(); }

</SCRIPT>

</HEAD>

<BODY onload="noBack();"

onpageshow="if (event.persisted) noBack();"onunload="">

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

functionselectBoxRemove(sourceID) {

//获得listbox的id

varsrc = document.getElementById(sourceID);

//循环listbox

for(varcount= 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中的所有项目还是非全选所有项目,代码如下:

1

2

3

4

5

6

functionlistboxSelectDeselect(listID, isSelect) {

varlistbox = document.getElementById(listID);

for(varcount=0; count < listbox.options.length; count++) {

listbox.options[count].selected = isSelect;

}

}

  13 在Listbox中项目的上下移动

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

functionlistbox_move(listID, direction) {

varlistbox = document.getElementById(listID);

varselIndex = listbox.selectedIndex;

if(-1 == selIndex) {

alert("Please select an option to move.");

return;

}

varincrement = -1;

if(direction =='up')

increment = -1;

else

increment = 1;

if((selIndex + increment) < 0 ||

(selIndex + increment) > (listbox.options.length-1)) {

return;

}

varselValue = listbox.options[selIndex].value;

varselText = 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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

functionlistbox_moveacross(sourceID, destID) {

varsrc = document.getElementById(sourceID);

vardest = document.getElementById(destID);

for(varcount=0; count < src.options.length; count++) {

if(src.options[count].selected ==true) {

varoption = src.options[count];

varnewOption = 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');

  15 快速初始化Javscript数组

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

1

2

3

varnumbers = [];

for(vari=1; numbers.push(i++)<100;);

//numbers = [0,1,2,3 ... 100]

  使用的是数组的push方法

  16 截取指定位数的小数

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

1

2

var num = 2.443242342;

alert(num.toFixed(2));

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

1

2

num = 500.2349;

result = num.toPrecision(4);//输出500.2

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

if(!Array.prototype.indexOf) {

Array.prototype.indexOf =function(obj, start) {

for(vari = (start || 0), j =this.length; i < j; i++) {

if(this[i] === obj) {returni; }

}

return-1;

}

}

if(!String.prototype.contains) {

String.prototype.contains =function(arg) {

return!!~this.indexOf(arg);

};

}

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

1

2

3

varhay ="a quick brown fox jumps over lazy dog";

varneedle ="jumps";

alert(hay.contains(needle));

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

functionremoveDuplicates(arr) {

vartemp = {};

for(vari = 0; i < arr.length; i++)

temp[arr[i]] =true;

varr = [];

for(varkintemp)

r.push(k);

returnr;

}

//用法

varfruits = ['apple','orange','peach','apple','strawberry','orange'];

varuniquefruits = removeDuplicates(fruits);

//输出 uniquefruits ['apple', 'orange', 'peach', 'strawberry'];

  19 去掉String中的多余空格

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

1

2

3

4

5

6

7

8

9

10

if(!String.prototype.trim) {

String.prototype.trim=function() {

returnthis.replace(/^\s+|\s+$/g,'');

};

}

//用法

varstr =" some string ";

str.trim();

//输出 str = "some string"

  20 Javascript中的重定向

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

1

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

  21 对URL进行编码

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

1

2

varmyOtherUrl =

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

http://viralpatel.net/blogs/javascript-tips-tricks/