21个js 技巧收藏
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
|
window.location.href = <a href= "http://viralpatel.net" >http://viralpatel.net</a>;
|
21 对URL进行编码
有的时候,需要对URL中的传递的进行编码,方法如下:
1
2
|
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
|
原文链接:http://viralpatel.net/blogs/javascript-tips-tricks/
转载于:https://www.cnblogs.com/sunShineJing/p/3487492.html
21个js 技巧收藏相关推荐
- js 技巧杂引(转)
js 技巧杂引(转) posted on 2005年9月28日 1:12 由 Snow 事件源对象 event.srcElement.tagName event.srcElement.type 捕获释 ...
- 常用网页使用js技巧收集(200多个)经典
常用网页使用js技巧收集(200多个)经典 1.文本框焦点问题 onBlur:当失去输入焦点后产生该事件 onFocus:当输入获得焦点后,产生该文件 Onchange:当文字值改变时,产生该事件 O ...
- JavaScript的一些实用技巧收藏
JavaScript的一些实用技巧收藏 [Copy to clipboard] CODE: 1. οncοntextmenu="window.event.returnValue=false& ...
- 高手新手都能用的140个电脑技巧 收藏
高手新手都能用的140个电脑技巧 收藏 1.重装WindowsXP不需再激活 如果你需要重装WindowsXP,通常必须重新激活.事实上只要在第一次激活时,备份好Windows/System32目 ...
- js技巧--转义符\的妙用
js技巧--转义符"\"的妙用 // blueDestiny, never-online // blueDestiny [at] 126.com 通常,我们在动态给定一个conta ...
- 一些冷门的JS技巧 顶
一些冷门的JS技巧 顶!!! 前端已经被玩儿坏了!像console.log()可以向控制台输出图片等炫酷的玩意已经不是什么新闻了,像用||操作符给变量赋默认值也是人尽皆知的旧闻了,今天看到Quo ...
- 火狐浏览器调试js技巧_充分利用Firefox的最佳技巧和调整
火狐浏览器调试js技巧 Firefox is one of the more popular web browsers that runs on Windows, Linux, and Mac OS ...
- UI界面如何制作?这些版式设计小技巧收藏好!
本文由:"学设计上兔课网"原创,图片素材来自网络,仅供学习分享 UI界面如何制作?这些版式设计小技巧收藏好!在做UI界面的时候,很多时候我们需要去看很多的产品进行竞品分析.市场调研 ...
- 分享21个JS抽奖转盘特效,36个JS表单验证,31个JS进度条,总有一款适合您
分享21个JS抽奖转盘特效,36个JS表单验证,31个JS进度条,总有一款适合您 下载链接:https://pan.baidu.com/s/1TWOGqes5J2baelO9qdItXg?pwd=ma ...
- 11 个对开发有帮助的 JS 技巧,进收藏夹当小词典吧!
作者:Orkhan Jafarov 译者:前端小智 来源: dev 点赞再看,微信搜索**[大迁世界],B站关注[前端小智]**这个没有大厂背景,但有着一股向上积极心态人.本文 GitHub http ...
最新文章
- mysql主从出现异常,处理方法
- 为了熟练掌握动态SQL你必须要知道Mybatis中的OGNL表达式
- python判断操作系统类型
- 在SqlServer存储过程中使用Cursor(游标)操作记录
- 在SD/MMC卡中可读写的FAT文件系统
- java sql 登录失败_java – 接收连接到SQL Server 2008的SQLException“用户登录失败”
- 阿里云-设备影子概览
- 跟我一起数据挖掘(19)——什么是数据挖掘(2)
- mac传输文件之airdrop
- 计算机编程语言排行榜—TIOBE世界编程语言排行榜(2021年11月份最新版)
- 独立t检验和配对t检验_配对学生的t检验是什么?
- 瞎琢磨先生のJava笔记之Java代码远程调用shell脚本
- 成就系统工程师的职业生涯
- git提交规范图-提问的智慧图谱-React 学习路线图- 达克效应
- 暑假出游 |近视配镜首选变色镜片
- 蚂蚁金服估值1500亿只是起点 阿里经济体一骑绝尘 腾讯望尘莫及
- 中国人民公安大学 网络对抗技术 15网安六区 杨益 201521460031
- 图书推荐:SQL Server 2012 T-SQL基础教程 Itzik Ben-Gan
- Elasticsearch插件:elasticsearch-sql安装和使用
- 桩机行进竣工图视频教程