当前位置: 首页 > news >正文

21个值得收藏的Javascript技巧

在本文中列出了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
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/zhgt/p/4278428.html

相关文章:

  • 43. Multiply Strings字符串相乘
  • displayport-2
  • 他山之石——运维平台哪家强?
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • String Boot中@Controller和@RestController的区别?
  • 加入lib
  • form 表单中input 使用disable属性
  • Android 设置按钮为透明
  • 订餐小程序新获利使商家摆脱第三方平台束缚
  • AVR Option -H must not be defined more than once: -H1895 【已解决】
  • 日常问题小记(交接篇)
  • 如何简单的将pdf文件转换成html超文本标记语言
  • css知多少(5)——选择器
  • Flutter完整开发实战详解(十、 深入图片加载流程)
  • 个人支付宝/微信/云闪付收款技术总览
  • [ JavaScript ] 数据结构与算法 —— 链表
  • [ 一起学React系列 -- 8 ] React中的文件上传
  • 【node学习】协程
  • 【剑指offer】让抽象问题具体化
  • Android Studio:GIT提交项目到远程仓库
  • Gradle 5.0 正式版发布
  • iOS高仿微信项目、阴影圆角渐变色效果、卡片动画、波浪动画、路由框架等源码...
  • react 代码优化(一) ——事件处理
  • Webpack4 学习笔记 - 01:webpack的安装和简单配置
  • 阿里云购买磁盘后挂载
  • 得到一个数组中任意X个元素的所有组合 即C(n,m)
  • 老板让我十分钟上手nx-admin
  • 前端技术周刊 2019-02-11 Serverless
  • 网页视频流m3u8/ts视频下载
  • 新手搭建网站的主要流程
  • 云栖大讲堂Java基础入门(三)- 阿里巴巴Java开发手册介绍
  • 智能网联汽车信息安全
  • 终端用户监控:真实用户监控还是模拟监控?
  • Java性能优化之JVM GC(垃圾回收机制)
  • Nginx惊现漏洞 百万网站面临“拖库”风险
  • ​ ​Redis(五)主从复制:主从模式介绍、配置、拓扑(一主一从结构、一主多从结构、树形主从结构)、原理(复制过程、​​​​​​​数据同步psync)、总结
  • #免费 苹果M系芯片Macbook电脑MacOS使用Bash脚本写入(读写)NTFS硬盘教程
  • (二十五)admin-boot项目之集成消息队列Rabbitmq
  • (附源码)spring boot建达集团公司平台 毕业设计 141538
  • (附源码)ssm学生管理系统 毕业设计 141543
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (五)关系数据库标准语言SQL
  • (转)jQuery 基础
  • (轉)JSON.stringify 语法实例讲解
  • **CI中自动类加载的用法总结
  • .NET Core 实现 Redis 批量查询指定格式的Key
  • .net 调用php,php 调用.net com组件 --
  • .NET 命令行参数包含应用程序路径吗?
  • .NET:自动将请求参数绑定到ASPX、ASHX和MVC(菜鸟必看)
  • .NET学习全景图
  • @Autowired和@Resource装配
  • @Controller和@RestController的区别?
  • @RequestParam,@RequestBody和@PathVariable 区别
  • [ 手记 ] 关于tomcat开机启动设置问题
  • [2]十道算法题【Java实现】