JavaScript小技巧
来源:互联网 发布:网络福禄克怎么测试 编辑:程序博客网 时间:2024/06/06 20:24
1、变量转换
但是转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,创建正则表达式的时候要使用/pattern/flags这样的简化形式。
想将format后的时间转换为时间对象?直接用Date的构造函数
想将一个标准的时间对象转换为unix时间戳?valueOf搞定之
下面的实例用的更绝
7、删除数组元素
大家也许会想为什么要用splice而不用delete,因为用delete将会在数组里留下一个空洞,而且后面的下标也并没有递减。
这样一句简单的话就可以判断是否为ie,太。。。
其实还有更多妙的方法,请看下面
学到这个瞬间觉得自己弱爆了。
其实利用原生的方法,可以更简单实现
当然最简洁的方法便是:
当前也可以这样
10、生成随机数
11、不用第三方变量交换两个变量的值
12、事件委派
举个简单的例子:html代码如下
js代码如下:
利用事件委派可以写出更加优雅的:
13、检测ie版本
15、判断属性是否存在
有的情况下,我们有更深的结构和需要更合适的检查的时候
其实最好的检测一个属性是否存在的方法为:
16、检测对象是否为数组
17、给函数传递对象
18、为replace方法传递一个函数
19、循环中使用标签
有时候循环当中嵌套循环,你可能想要退出某一层循环,之前总是用一个标志变量来判断,现在才知道有更好的方法
20、对数组进行去重
或者如下:
其实最优的方法是这样的
使用范例:
21、查找字符串中出现最多的字符及个数
再反转义
参数范围为0~20,不写默认0
- var myVar = "3.14159",
- str = ""+ myVar,// to string
- int = ~~myVar, // to integer
- float = 1*myVar, // to float
- bool = !!myVar, /* to boolean - any string with length
- and any number except 0 are true */
- array = [myVar]; // to array
- //字符型变量参与运算时,JS会自动将其转换为数值型(如果无法转化,变为NaN)
- '10.567890' | 0
- //结果: 10
- //JS里面的所有数值型都是双精度浮点数,因此,JS在进行位运算时,会首先将这些数字运算数转换为整数,然后再执行运算
- //| 是二进制或, x|0 永远等于x;^为异或,同0异1,所以 x^0 还是永远等于x;至于~是按位取反,搞了两次以后值当然是一样的
- '10.567890' ^ 0
- //结果: 10
- - 2.23456789 | 0
- //结果: -2
- ~~-2.23456789
- //结果: -2
3、日期转换
- //JS本身时间的内部表示形式就是Unix时间戳,以毫秒为单位记录着当前距离1970年1月1日0点的时间单位
- var d = +new Date(); //1295698416792
想得到format后的时间?现在不用再get年月日时分秒了,三步搞定
- var temp = new Date();
- var regex = /\//g;
- (temp.toLocaleDateString() + ' ' + temp.toLocaleTimeString().slice(2)).replace(regex,'-');
- // "2015-5-7 9:04:10"
- new Date("2015-5-7 9:04:10");
- // Thu May 07 2015 09:04:10 GMT+0800 (CST)
- (new Date).valueOf();
- // 1431004132641
- var arr =[].slice.call(arguments)
- function test() {
- var res = ['item1', 'item2']
- res = res.concat(Array.prototype.slice.call(arguments)) //方法1
- Array.prototype.push.apply(res, arguments) //方法2
- }
- (int).toString(16); // converts int to hex, eg 12 => "C"
- (int).toString(8); // converts int to octal, eg. 12 => "14"
- parseInt(string,16) // converts hex to int, eg. "FF" => 255
- parseInt(string,8) // converts octal to int, eg. "20" => 16
- var a = [1,2,3,7,8,9];
- var b = [4,5,6];
- var insertIndex = 3;
- a.splice.apply(a, Array.prototype.concat(insertIndex, 0, b));
7、删除数组元素
- var a = [1,2,3,4,5];
- a.splice(3,1); //a = [1,2,3,5]
- var ie = /*@cc_on !@*/false;
其实还有更多妙的方法,请看下面
- // 貌似是最短的,利用IE不支持标准的ECMAscript中数组末逗号忽略的机制
- var ie = !-[1,];
- // 利用了IE的条件注释
- var ie = /*@cc_on!@*/false;
- // 还是条件注释
- var ie//@cc_on=1;
- // IE不支持垂直制表符
- var ie = '\v'=='v';
- // 原理同上
- var ie = !+"\v1";
9、尽量利用原生方法
要找一组数字中的最大数,我们可能会写一个循环,例如:- var numbers = [3,342,23,22,124];
- var max = 0;
- for(var i=0;i<numbers.length;i++){
- if(numbers[i] > max){
- max = numbers[i];
- }
- }
- alert(max);
- var numbers = [3,342,23,22,124];
- numbers.sort(function(a,b){return b - a});
- alert(numbers[0]);
- Math.max(12,123,3,2,433,4); // returns 433
- Math.max.apply(Math, [12, 123, 3, 2, 433, 4]) //取最大值
- Math.min.apply(Math, [12, 123, 3, 2, 433, 4]) //取最小值
10、生成随机数
- Math.random().toString(16).substring(2);// toString() 函数的参数为基底,范围为2~36。
- Math.random().toString(36).substring(2);
11、不用第三方变量交换两个变量的值
- a=[b, b=a][0];
12、事件委派
举个简单的例子:html代码如下
- <h2>Great Web resources</h2>
- <ul id="resources">
- <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>
- <li><a href="http://sitepoint.com">Sitepoint</a></li>
- <li><a href="http://alistapart.com">A List Apart</a></li>
- <li><a href="http://yuiblog.com">YUI Blog</a></li>
- <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>
- <li><a href="http://oddlyspecific.com">Oddly specific</a></li>
- </ul>
- // Classic event handling example
- (function(){
- var resources = document.getElementById('resources');
- var links = resources.getElementsByTagName('a');
- var all = links.length;
- for(var i=0;i<all;i++){
- // Attach a listener to each link
- links[i].addEventListener('click',handler,false);
- };
- function handler(e){
- var x = e.target; // Get the link that was clicked
- alert(x);
- e.preventDefault();
- };
- })();
- (function(){
- var resources = document.getElementById('resources');
- resources.addEventListener('click',handler,false);
- function handler(e){
- var x = e.target; // get the link tha
- if(x.nodeName.toLowerCase() === 'a'){
- alert('Event delegation:' + x);
- e.preventDefault();
- }
- };
- })();
13、检测ie版本
- var _IE = (function(){
- var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
- while (
- div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
- all[0]
- );
- return v > 4 ? v : false ;
- }());
14、javaScript版本检测
- var JS_ver = [];
- (Number.prototype.toFixed)?JS_ver.push("1.5"):false;
- ([].indexOf && [].forEach)?JS_ver.push("1.6"):false;
- ((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;
- ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;
- ("".trimLeft)?JS_ver.push("1.8.1"):false;
- JS_ver.supports = function()
- {
- if (arguments[0])
- return (!!~this.join().indexOf(arguments[0] +",") +",");
- else
- return (this[this.length-1]);
- }
- alert("Latest Javascript version supported: "+ JS_ver.supports());
- alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));
15、判断属性是否存在
- // BAD: This will cause an error in code when foo is undefined
- if (foo) {
- doSomething();
- }
- // GOOD: This doesn't cause any errors. However, even when
- // foo is set to NULL or false, the condition validates as true
- if (typeof foo != "undefined") {
- doSomething();
- }
- // BETTER: This doesn't cause any errors and in addition
- // values NULL or false won't validate as true
- if (window.foo) {
- doSomething();
- }
- // UGLY: we have to proof existence of every
- // object before we can be sure property actually exists
- if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
- doSomething();
- }
- if("opera" in window){
- console.log("OPERA");
- }else{
- console.log("NOT OPERA");
- }
16、检测对象是否为数组
- var obj=[];
- Object.prototype.toString.call(obj)=="[object Array]";
17、给函数传递对象
- function doSomething() {
- // Leaves the function if nothing is passed
- if (!arguments[0]) {
- return false;
- }
- var oArgs = arguments[0]
- arg0 = oArgs.arg0 || "",
- arg1 = oArgs.arg1 || "",
- arg2 = oArgs.arg2 || 0,
- arg3 = oArgs.arg3 || [],
- arg4 = oArgs.arg4 || false;
- }
- doSomething({
- arg1 : "foo",
- arg2 : 5,
- arg4 : false
- });
18、为replace方法传递一个函数
- var sFlop = "Flop: [Ah] [Ks] [7c]";
- var aValues = {"A":"Ace","K":"King",7:"Seven"};
- var aSuits = {"h":"Hearts","s":"Spades",
- "d":"Diamonds","c":"Clubs"};
- sFlop = sFlop.replace(/\[\w+\]/gi, function(match) {
- match = match.replace(match[2], aSuits[match[2]]);
- match = match.replace(match[1], aValues[match[1]] +" of ");
- return match;
- });
- // string sFlop now contains:
- // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"
19、循环中使用标签
有时候循环当中嵌套循环,你可能想要退出某一层循环,之前总是用一个标志变量来判断,现在才知道有更好的方法
- outerloop:
- for (var iI=0;iI<5;iI++) {
- if (somethingIsTrue()) {
- // Breaks the outer loop iteration
- break outerloop;
- }
- innerloop:
- for (var iA=0;iA<5;iA++) {
- if (somethingElseIsTrue()) {
- // Breaks the inner loop iteration
- break innerloop;
- }
- }
- }
20、对数组进行去重
- /*
- *@desc:对数组进行去重操作,返回一个没有重复元素的新数组
- */
- function unique(target) {
- var result = [];
- loop: for (var i = 0, n = target.length; i < n; i++) {
- for (var x = i + 1; x < n; x++) {
- if (target[x] === target[i]) {
- continue loop;
- }
- }
- result.push(target[i]);
- }
- return result;
- }
- Array.prototype.distinct = function () {
- var newArr = [],obj = {};
- for(var i=0, len = this.length; i < len; i++){
- if(!obj[typeof(this[i]) + this[i]]){
- newArr.push(this[i]);
- obj[typeof(this[i]) + this[i]] = 'new';
- }
- }
- return newArr;
- }
- Array.prototype.distinct = function () {
- var sameObj = function(a, b){
- var tag = true;
- if(!a || !b) return false;
- for(var x in a){
- if(!b[x]) return false;
- if(typeof(a[x]) === 'object'){
- tag = sameObj(a[x],b[x]);
- } else {
- if(a[x]!==b[x])
- return false;
- }
- }
- return tag;
- }
- var newArr = [], obj = {};
- for(var i = 0, len = this.length; i < len; i++){
- if(!sameObj(obj[typeof(this[i]) + this[i]], this[i])){
- newArr.push(this[i]);
- obj[typeof(this[i]) + this[i]] = this[i];
- }
- }
- return newArr;
- }
- var arr=[{name:"tom",age:12},{name:"lily",age:22},{name:"lilei",age:12}];
- var newArr=arr.distinct(function(ele){
- return ele.age;
- });
21、查找字符串中出现最多的字符及个数
- var i, len, maxobj='', maxnum=0, obj={};
- var arr = "sdjksfssscfssdd";
- for(i = 0, len = arr.length; i < len; i++){
- obj[arr[i]] ? obj[arr[i]]++ : obj[arr[i]] = 1;
- if(maxnum < obj[arr[i]]){
- maxnum = obj[arr[i]];
- maxobj = arr[i];
- }
- }
- alert(maxobj + "在数组中出现了" + maxnum + "次");
22、& (按位与)
判断一个数是否为2的n次幂,可以将其与自身减一相与
- var number = 4
- (number & number -1) === 0 // true
23、^ (按位异或)
不同第三个变量,就可以交换两个变量的值
- var a = 4,b = 3
- a = a ^ b // 7
- b = a ^ b // 4
- a = b ^ a // 3
24、一元加可以快速将字符串的数字转换为数学数字,即
- var number = "23"
- typeof number // string
- typeof +number // number
25、转义URI
需要将url当做参数在路由中传递,现在转义之
- var url = encodeURIComponent('http://segmentfault.com/questions/newest')
- // "http%3A%2F%2Fsegmentfault.com%2Fquestions%2Fnewest"
- decodeURIComponent(url)
- // "http://segmentfault.com/questions/newest"
26、Number
希望保留小数点后的几位小数,不用再做字符串截取了,toFixed拿走
- number.toFixed() // "12346"
- number.toFixed(3) // "12345.679"
- number.toFixed(6) // "12345.678900"
27、toExponential()
toExponential() 方法可把对象的值转换成指数计数法。
- var num = 10000.1234;
- console.log(num.toExponential()); //1.00001234e+4
- console.log(num.toExponential(2)); //1.00e+4
- console.log(num.toExponential(10)); //1.0000123400e+4
28、toPrecision()
toPrecision() 方法可将数值格式化为一个十进制数形式的字符串
参数num是可选的。用于控制数字的精度。该参数是 1 ~ 21 之间(且包括 1 和 21)的值。如果省略了该参数,则调用方法 toString(),而不是把数字转换成十进制的值。
- var num = 10000.1234;
- console.log(num.toPrecision()); //10000.1234
- console.log(num.toPrecision(2)); //1.0e+4
- console.log(num.toPrecision(10)); //10000.12340
0 0
- 【JavaScript】JavaScript小技巧
- javascript小技巧
- javascript小技巧
- javascript小技巧
- javascript小技巧
- javascript小技巧
- javascript小技巧
- javascript小技巧
- javascript小技巧
- javascript小技巧
- javascript小技巧 (转)
- javascript一些小技巧
- javascript小技巧
- JavaScript小技巧
- javascript小技巧
- javascript 小技巧
- javascript小技巧
- javascript小技巧
- Apache安装问题:configure: error: APR not found . Please read the documentation
- Golang(Go语言)中append函数返回值必须有变量接收的原因探究
- java 设计模式之迪米特法则
- 侧滑菜单
- Qt动态库调试方法2
- JavaScript小技巧
- 救命神文!应对ubuntu磁盘空间不足(已解决)
- IIS发布后图标或者字体不能显示
- 如何在楼板上开槽
- Sublime Text 代码编辑器
- MySQL中select filed from table where field in (....)语句的排序问题
- ViewPagerIndicator+viewpager指示器详解
- Swift:如何判断一个对象是否是某个类(或其子类)的实例
- Java.io.File.mkdirs()方法实例