JS常用

  1. 对象转json字符串

     var obj = [{"name":"dog","age":10},{"name":"cat","age":8}];
     var str = JSON.stringify(obj);
     //打印对象成员
     console.log(obj[0].name);
     console.log(obj[1].age);
     //打印JSON字符串
     console.log(str);
    
  2. json字符串转对象

     var str = '[{"name":"dog","age":10},{"name":"cat","age":8}]';
     var obj = JSON.parse(str);
     //打印对象成员
     console.log(obj[0].name);
     console.log(obj[1].age);
     //打印JSON字符串
     console.log(str);
    
  3. 从url获取get参数的值

     http://localhost/index.html?id=62605
     var pattern=new RegExp(/id=(\d+)/g);
     var arr=pattern.exec(location.search);
     if(arr !=null){
         var id=arr[1];
     }else{
         return false;
     }
    
  4. 立即执行函数

     (function () {
         //要执行的代码
     })()
    
  5. js时间转日期(自动处理为用户系统设定时区的时间)

     var i,str;
     var date=new Date(1488002361000);
     var arr=[
     date.getFullYear(),
     date.getMonth()+1,
     date.getDate(),
     date.getHours(),
     date.getMinutes(),
     date.getSeconds()
     ];
     for(i=1;i<=5;i++){
     arr[i]=("0"+arr[i]).slice(-2);
     }
     str=arr[0]+'-'+arr[1]+'-'+arr[2]+' '+arr[3]+':'+arr[4]+':'+arr[5];
     console.log(str);
    
@耿志环 2012-∞ 冀ICP备17033181号, powered by Gitbook修订: 2019-01-11 16:52:19

results matching ""

    No results matching ""