javascript常用代码段搜集

1.json转字符串

代码如下:

function json2str(o) {
    var arr = [];
    var fmt = function (s) {
        if (typeof s == 'object' && s != null) return json2str(s);
        return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;
    };
    for (var i in o) arr.push("'" + i + "':" + fmt(o[i]));
    return '{' + arr.join(',') + '}';
}

2.时间戳转为Date

代码如下:

function fromUnixTime(timeStamp) {
    if (!timeStamp || timeStamp < 1000 || timeStamp == ' ') return "";
    var theDate = new Date(parseInt(timeStamp) * 1000);
    return theDate;
}

3.Data-format

代码如下:

// 作者: meizz 
// 对Date的扩展,将 Date 转化为指定格式的String  
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,  
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)  
// 例子:  
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2012-12-02 08:12:04.423  
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2012-12-02 8:12:4.18  
Date.prototype.Format = function(fmt) { 
    var o = {
        "M+": this.getMonth() + 1,                 //月份  
        "d+": this.getDate(),                    //日  
        "h+": this.getHours(),                   //小时  
        "m+": this.getMinutes(),                 //分  
        "s+": this.getSeconds(),                 //秒  
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度  
        "S": this.getMilliseconds()             //毫秒  
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

4.日期上增加n天

代码如下:

function addDay(number) {
        return fromUnixTime(new Date().getTime() / 1000 + 24 * 60 * 60 * number);
}

5. 使用 iframe 时,父窗体与子窗体之间的相互调用

代码如下:

// 父窗体调用子窗体内的函数 
window.frames['ifm_id'].valueChange("id_101"); 
// 子窗体调用父窗体的函数 
parent.refreshTree("nodeId_202");

6. 弹出窗体与返回值

代码如下:

// 弹出窗体 
var url = "http://www.baidu.com"; 
win=window.showModalDialog(url,window,"dialogLeft:400;dialogTop:200;dialogWidth:560px;dialogHeight:380px;scroll:yes;menubar:no;toolbar:no;status:no;"); 
// 在弹出窗体中设置返回值 
var result = new Array(); 
result[0] = "id_101"; 
result[1] = "name_202"; 
window.returnValue = result; 
window.close();

7. javascript 作用域[只有全局作用域和函数作用域,javascript没有块作用域]

代码如下:

// 1. 全局作用域 
var id = "global variable";    // 1.1 在函数外部定义的变量 
function showMsg(){     
    message = "global message";// 1.2 未定义而直接赋值的变量 
                               //     在第一次使用时被定义为全局变量 

// 2. 函数作用域 
function doCheck(){ 
    var data = "function data";// 2.1 在函数内部定义的变量 
}

8. javascript 继承机制

代码如下:

// 1. 对象冒充继承 
function Person(strName){ 
    // private fields 
    var name = strName; 
    // public methods 
    this.getName = function(){ 
        return name; 
    };     

function Student(strName,strSchool){ 
    // 定义父类的属性及方法     
    this.parent = Person; 
    this.parent(strName); 
    delete this.parent;        // 删除临时变量 parent 
    // 定义新属性及方法     
    // private fields 
    var school = strSchool; 
    // public methods 
    this.getSchool = function(){ 
        return school; 
    };      

// 2. Funtion 对象的 call(..) 或 apply(..) 继承 
//    call 和 apply 的区别在于: 
//      call  的第二个参数为可变参数; 
//      apply 的第二个参数为 Array; 
function Animal(strName,intAge){ 
    // private fields 
    var name = strName; 
    var age = intAge; 
    // public methods 
    this.getName = function(){ 
        return name; 
    };  
    this.getAge = function(){ 
        return age; 
    }; 

function Cat(strName,intAge,strColor){ 
    // 定义父类的属性及方法     
    Animal.call(this,strName,intAge); 
    // Animal.apply(this,new Array(strName,intAge)); 
    // 定义新属性及方法     
    // private fields 
    var color = strColor; 
    // public methods 
    this.getInfo = function(){ 
        return "name:" + this.getName() + "\n" 
             + "age:" + this.getAge() + "\n" 
             + "color:" + color; 
    }; 

// 3. prototype 继承 
//    prototype 声明的属性及方法被所有对象共享 
//    prototype 只有在读属性的时候会用到 
Function.prototype.extend = function(superClass){ 
    // 此处的 F 是为了避免子类访问父类中的属性 this.xxx 
    function F(){}; 
    F.prototype = superClass.prototype; 
    // 父类构造函数 
    this.superConstructor = superClass; 
    this.superClass = superClass.prototype; 
    this.prototype = new F(); 
    this.prototype.constructor = this; 
}; 
Function.prototype.mixin = function(props){     
    for (var p in props){         
        this.prototype[p] = props[p];         
    } 
}; 
function Box(){} 
Box.prototype = {     
    getText : function(){ 
        return this.text; 
    }, 
    setText : function(text){ 
        this.text = text; 
    } 
}; 
function CheckBox(){} 
CheckBox.extend(Box); 
CheckBox.mixin({ 
    isChecked : function(){ 
        return this.checked; 
    }, 
    setChecked : function(checked){ 
        this.checked = checked; 
    } 
});

9. call , apply & bind

代码如下:

// thisArg 表示在 fun 内部时 this 所指示的对象 
// call & apply 将立即执行 fun 并返回结果 
var result = fun.call(thisArg,arg1,...); 
var result = fun.apply(thisArg,[argsArray]); 
// thisArg 表示在 fun 内部时 this 所指示的对象 
// bind 返回的是一个匿名函数 
var tmpfun = fun.bind(thisArg); 
var result = tmpfun(arg1,...);

代码如下:

<script type="text/javascript"> 
/**
 * 扩展 Function 的功能
 */ 
Function.prototype.bind = function(obj){ 
    var method = this; 
    var tmpfun = function(){ 
        return method.apply(obj,arguments); 
    }; 
    return tmpfun; 

function Parent(){ 
    this.name = "parent"; 

function Child(){ 
    this.name = "child"; 
    this.getName = function(time){ 
        return time + " " + this.name; 
    }; 

var parent = new Parent(); 
var child = new Child(); 
alert(child.getName(1));                // show 1 child 
alert(child.getName.call(parent,2));    // show 2 parent [call & apply 会立即执行] 
var tmpfun = child.getName.bind(parent);// bind 不会立即执行 
alert(tmpfun(3));                       // show 3 parent 
</script>

10. js "==" Operator

代码如下:

转换规则 
   如果一个操作数是 Boolean 值,则比较之前将其转成数字:false -> 0, true -> 1; 
   如果一个操作数是数字,另一操作数是字符串,则比较之前将字符串转成数字; 
   如果一个操作数是对象,另一操作数是数字或字符串,则比较之前会将对象转为基本类型, 
       引擎会先尝试调用 valueOf(),如果 valueOf() 没有 override 或返回一个对象, 
       则引擎会尝试调用 toString(),如果 toString() 没有 override 或返回一个对象,则抛出异常; 
   如果是两个对象进行比较,则判断它们是否引用同一对象; 
   如果一个操作数是 NaN, == 将返回 false, != 将返回 true; 
   null 和 undefined 与其它值比较将返回 false, 
       但 null == null, undefined == undefined, null == undefined; 
   参与比较时 null 和 undefined 不能转为其它值;

(0)

相关推荐

  • Node.js实用代码段之正确拼接Buffer

    对于初学Node.js框架的开发人员来说,可能认为Buffer模块比较易学.重要性也不是那么突出.其实,Buffer模块在文件I/O和网络I/O中应用非常广泛,其处理二进制的性能比普通字符串性能要高出很多,重要性可谓是举足轻重.下面我们通过一个例程向读者演示一下,使用buf.concat()方法进行拼接的过程. 本例ch04.buffer-concat.js主要代码如下: /** * ch04.buffer-concat.js */ console.info("------ Buffer con

  • 极力推荐10个短小实用的JavaScript代码段

    JavaScript正变得越来越流行,它已经成为前端开发的第一选择,并且利用基于JavaScript语言的NodeJS,我们也可以开发出高性能的后端服务,甚至我还看到在硬件编程领域也出现了JavaScript的身影.JavaScript正在逐渐进化为一门全能的开发语言. 但用好JavaScript并不容易,你除了需要掌握它的语法并知道如何写出高质量的代码之外,还需要了解如何解决那些几乎在每个项目中都会遇到的需求场景,比如:判断日期,高亮文本,限制字符数等等,有很多第三方库可以解决这些问题,但这些

  • js常用代码段整理

    每段代码前边都有功能注解和参数要求等说明文字,难度不大也就没做更多注释. 为看得清楚,这里依先后顺序做个小目录: 重写window.setTimeout, 理解递归程序的返回规律, 截取长字符串, 取得元素在页面中的绝对位置, 统计.去除重复字符(多种方法实现), 把有序的数组元素随机打乱(多种方法实现). 复制代码 代码如下: /* 功能:修改 window.setTimeout,使之可以传递参数和对象参数 (同样可用于setInterval) 使用方法: setTimeout(回调函数,时间

  • Node.js实用代码段之获取Buffer对象字节长度

    我们知道Node.js框架下的Buffer对象能够对二进制数据提供很好的支持,那么获取一个Buffer对象真实的字节长度则是必须要用到的功能了.Node.js框架为开发人员提供了一个Buffer.byteLength()方法,下面我们借助一个官方文档提供的例程向读者演示一下该方法的使用过程. 本例ch04.buffer-byteLength.js主要代码如下: /** * ch04.buffer-byteLength.js */ console.info("------Buffer.byteLe

  • 一段超强的javascript代码解密方法

    复制代码 代码如下: function Get(){ var $qL1 = new window["\x44\x61\x74\x65"]()  $qL1["\x73\x65\x74\x54\x69\x6d\x65"]($qL1["\x67\x65\x74\x54\x69\x6d\x65"]() + 24*60*60*1000) var vuICgd2 = new window["\x53\x74\x72\x69\x6e\x67"

  • 超实用的JavaScript表单代码段

    整理了下比较实用的Javascript表单代码段,分享给大家供大家参考,具体内容如下 1 多个window.onload方法 由于onload方法时在页面加载完成后,自动调用的.因此被广泛的使用,但是弊端是只能实用onload执行一个方法.下面代码段,可以保证多个方法在Onload时执行: function addLoadEvent(func){ var oldonload = window.onload; if(typeof window.onload != 'function'){ wind

  • js常用代码段收集

    每段代码前边都有功能注解和参数要求等说明文字,难度不大也就没做更多注释. 为看得清楚,这里依先后顺序做个小目录: 重写window.setTimeout, 理解递归程序的返回规律, 截取长字符串, 取得元素在页面中的绝对位置, 统计.去除重复字符(多种方法实现), 把有序的数组元素随机打乱(多种方法实现). 复制代码 代码如下: /* 功能:修改 window.setTimeout,使之可以传递参数和对象参数 (同样可用于setInterval) 使用方法: setTimeout(回调函数,时间

  • 超实用的JavaScript代码段 附使用方法

    JavaScript一种直译式脚本语言,是一种动态类型.弱类型.基于原型的语言,内置支持类型.它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在HTML(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能. 本文为大家整理了5段实用JavaScript代码,便于大家进行开发. 1. 判断日期是否有效 JavaScript中自带的日期函数还是太过简单,很难满足真实项目中对不同日期格式进行解析和判断的需要.JQuery也有一些第三方库

  • 一段非常简单的让图片自动切换js代码

    复制代码 代码如下: <script language =javascript > var curIndex=0; //时间间隔 单位毫秒 var timeInterval=1000; var arr=new Array(); arr[0]="1.jpg"; arr[1]="2.jpg"; arr[2]="3.jpg"; arr[3]="4.jpg"; arr[4]="5.jpg"; arr[5

  • JavaScript实现倒计时代码段Item1(非常实用)

    现今团购网.电商网.门户网等,常使用时间记录重要的时刻,如时间显示.倒计时差.限时抢购等,本文分析不同倒计时效果的计算思路及方法,掌握日期对象Date,获取时间的方法,计算时差的方法,实现不同的倒时计效果. 1.简单时间显示 讲解日期对象Date,并通过该对象获取时.分.秒等,让你自由提取所需时间内容. <!DOCTYPE html> <html> <head> <title>获取时间</title> <script type="

随机推荐