21个值得收藏的Javascript技巧
1 Javascript数组转换为CSV格式
首先考虑如下的应用场景,有一个Javscript的字符型(或者数值型)数组,现在需要转换为以逗号分割的CSV格式文件。则我们可以使用如下的小技巧,代码如下:
1
2
|
var fruits = [ 'apple' , 'peaches' , 'oranges' , 'mangoes' ]; var str = fruits.valueOf(); |
输出:apple,peaches,oranges,mangoes
其中,valueOf()方法会将Javascript数组转变为逗号隔开的字符串。要注意的是,如果想不使用逗号分割,比如用|号分割,则请使用join方法,如下:
1
2
|
var fruits = [ 'apple' , 'peaches' , 'oranges' , 'mangoes' ]; var str = fruits.join( "|" ); |
输出: apple|peaches|oranges|mangoes
2 将CSV格式重新转换回Javscript数组
那么如何将一个CSV格式的字符串转变回Javascript数组呢?可以使用split()方法,就可以使用任何指定的字符去分隔,代码如下:
1
2
|
var str = "apple, peaches, oranges, mangoes" ; var fruitsArray = str.split( "," ); |
输出 fruitsArray[0]: apple
3 根据索引移除数组中的某个元素
假如需要从Javascript数组中移除某个元素,可以使用splice方法,该方法将根据传入参数n,移除数组中移除第n个元素(Javascript数组中从第0位开始计算)。
1
2
3
4
5
6
7
8
9
10
11
|
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 根据元素的值移除数组元素中的值
下面这个技巧是很实用的,是根据给定的值去删除数组中的元素,代码如下:
1
2
3
4
5
6
7
8
9
10
11
|
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的方法去实现,如下代码:
1
2
3
4
5
6
7
8
9
10
11
|
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 通过字符串指定的方式动态调用某个方法
有的时候,需要在运行时,动态调用某个已经存在的方法,并为其传入参数。这个如何实现呢?下面的代码可以:
1
2
3
4
5
6
|
var strFun = "someFunction" ; //someFunction 为已经定义的方法名 var strParam = "this is the parameter" ; //要传入方法的参数 var fn = window[strFun]; //调用方法传入参数 fn(strParam); |
6 产生1到N的随机数
1
2
3
4
5
6
7
|
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技巧是十分有用的,代码如下:
1
2
3
4
5
6
7
8
9
|
<script language= "javascript" > function fnUnloadHandler() { 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
|
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 完全禁止使用后退键
下面的技巧放在页面中,则可以防止用户点后退键,这在一些情况下是需要的。代码如下:
1
2
3
4
5
6
7
|
<SCRIPT type= "text/javascript" > window.history.forward(); function noBack() { 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
|
function selectBoxRemove(sourceID) { //获得listbox的id var src = document.getElementById(sourceID); //循环listbox 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中的所有项目还是非全选所有项目,代码如下:
1
2
3
4
5
6
|
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中项目的上下移动
下面的代码,给出了在一个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
|
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 = -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 |
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
|
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' ); |
15 快速初始化Javscript数组
下面的方法,给出了一种快速初始化Javscript数组的方法,代码如下:
1
2
3
|
var numbers = []; for ( var i=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 ( 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方法,使用的方法如下:
1
2
3
|
var hay = "a quick brown fox jumps over lazy dog" ; var needle = "jumps" ; alert(hay.contains(needle)); |
18 去掉Javscript数组中的重复元素
下面的代码可以去掉Javascript数组中的重复元素,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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']; |
19 去掉String中的多余空格
下面的代码会为String增加一个trim()方法,代码如下:
1
2
3
4
5
6
7
8
9
10
|
if (!String.prototype.trim) { String.prototype.trim= function () { return this .replace(/^\s+|\s+$/g, '' ); }; } //用法 var str = " some string " ; str.trim(); //输出 str = "some string" |
20 Javascript中的重定向
在Javascript中,可以实现重定向,方法如下:
1
|
|
21 对URL进行编码
有的时候,需要对URL中的传递的进行编码,方法如下:
1
2
|
var myOtherUrl = |
21个值得收藏的Javascript技巧的更多相关文章
- 值得收藏的Javascript代码
1 Javascript数组转换为CSV格式 首先考虑如下的应用场景,有一个Javscript的字符型(或者数值型)数组,现在需要转换为以逗号分割的CSV格式文件.则我们可以使用如下的小技巧,代码如 ...
- Intellij IDEA神器值得收藏的小技巧
概述 Intellij IDEA真是越用越觉得它强大,它总是在我们写代码的时候,不时给我们来个小惊喜.出于对Intellij IDEA的喜爱,我决定写一个与其相关的专栏或者系列,把一些好用的Intel ...
- 45个值得收藏的 CSS 形状
摘要: CSS炫技. 原文:45个值得收藏的 CSS 形状 作者:前端小智 Fundebug经授权转载,版权归原作者所有. CSS能够生成各种形状.正方形和矩形很容易,因为它们是 web 的自然形状. ...
- mac设计师系列 Adobe “全家桶” 15款设计软件 值得收藏!
文章素材来源:风云社区.简书 文章收录于:风云社区 www.scoee.com,提供1700多款mac软件下载 Adobe Creative Cloud 全线产品均可开放下载(简称Adobe CC 全 ...
- 原生JavaScript技巧大收集100个
原生JavaScript技巧大收集 1.原生JavaScript实现字符串长度截取function cutstr(str, len) { var temp; var icount = 0; var p ...
- div+css样式命名规则,值得收藏
div+css样式命名规则,值得收藏 头:header 内容:content/container 尾:footer 导航:nav 侧栏:sidebar 栏目:column 页面外围控制整体布局宽度:w ...
- web前端/移动端H5博客专家博客大全--值得收藏的前端技术大牛博客地址
web前端/移动端H5博客专家博客大全--值得收藏的前端技术大牛博客地址 Huang Jie Blog .Com-前端开发 http://www.huangjieblog.com/?feed=rs ...
- 【转】45个实用的JavaScript技巧、窍门和最佳实践
原文:https://colobu.com/2014/09/23/45-Useful-JavaScript-Tips,-Tricks-and-Best-Practices/ 目录 [−] 列表 第一次 ...
- ABP(现代ASP.NET样板开发框架)系列之21、ABP展现层——Javascript函数库
点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之21.ABP展现层——Javascript函数库 ABP是“ASP.NET Boilerplate Project ...
随机推荐
- C# MySQL数据库的备份 还原 初始化
// 执行创建数据库操作 this.GetExecute(G_Con, "create database if not exists NEWDB"); this.sqlAddres ...
- myeclipse中自己手动配置maven
第一步,配置myeclipse的jdk,因为myeclipse默认的是运行在jre之上,而maven是在jdk之上 第二步,配置maven:
- 超级强大的SVG SMIL animation动画详解
本文花费精力惊人,具有先驱前瞻性,转载规则以及申明见文末,当心予以追究.本文地址:http://www.zhangxinxu.com/wordpress/?p=4333 //zxx: 本文的SVG在有 ...
- appium自动化测试
appium官网:http://appium.io/index.html?lang=zh Requirements Your environment needs to be setup for the ...
- (六)Android中Service通信
一.启动Service并传递参数 传递参数时只需在startService启动的Intent中传入数据便可,接收参数时可在onStartCommand函数中通过读取第一个参数Intent的内容来实现 ...
- Jquery库自带的动画效果方法记录
1.显示和隐藏hide()和show() <script type="text/javascript"> $(function() { ...
- C#高效分页代码(不用存储过程)
首先创建一张表(要求ID自动编号): create table redheadedfile ( id ,), filenames ), senduser ), primary key(id) ) 然后 ...
- Python基础:11.2_函数调用
我们已经接触过函数(function)的参数(arguments)传递.当时我们根据位置,传递对应的参数.这种参数传递的方式被称为函数参数的位置传递. 我们将接触更多的参数传递方式. 回忆一下位置传递 ...
- Servle原理
这篇博客将以Tomcat为例讲一讲Servlet的原理 Servlet容器 Servlet与Servlet容器的关系举个不恰当的例子就像枪和子弹的关系.而Servlet就是子弹,容器就是枪.子弹都有统 ...
- 多个DLL合并,DLL合并到EXE
1:) 下载 http://download.microsoft.com/download/1/3/4/1347C99E-9DFB-4252-8F6D-A3129A069F79/ILMerge.msi ...