大飞_dafei

导航

JavaScript里不为人知的秘密(03)之常见使用

JavaScript里不为人知的秘密(03)之常见使用

01)判断空对象

Object.keys({}).length; // 长度为0
Object.keys({foo: "bar"}).length; // 长度为1

Object.keys([]).length; // 长度为0
Object.keys(["fei"]).length; // 长度为1

02)常见加密解密

// Base64的编码与解码
let foo = "Hello fei";
window.btoa(foo); // SGVsbG8gZmVp
window.atob("SGVsbG8gZmVp"); // Hello fei

//  url 编码解码
let url = "http://github.com/search?name=1 2 3 $age=456";
encodeURI(url); // http://github.com/search?name=1%202%203%20$age=456
decodeURI("http://github.com/search?name=1%202%203%20$age=456");

// url 中参数编码解码
let bar = "a=123&b=456";
encodeURIComponent(bar); // a%3D123%26b%3D456
decodeURIComponent("a%3D123%26b%3D456"); // a=123&b=456

03) Blob 和 String相互转换

// 将String字符串转换成Blob对象
var blob = new Blob(['daFei'], {
    type: 'text/plain'
});
console.log(blob);

//将Blob 对象转换成字符串
var reader = new FileReader();
reader.readAsText(blob, 'utf-8');
reader.onload = function (e) {
    console.info(reader.result);
}

 04) 参数

解构参数  和  方法参数

// 解构参数
function foo({name = "daFei", age = 18}={}) {
    console.log(name,age);
}
foo({name:"foo",age:20});
foo({age:22});

// 方法参数
function bar(name="daFei",callBack) {
    if (callBack) {
        callBack();
    }else{
        console.log("没有执行");
    }
}
bar("bar", () => {
    console.log("开始执行");
});
bar("bar2")

 05) 秒转为小时分钟秒

  /**
   * 秒转为小时
   * @param value  秒
   * @returns {string}
   */
  const timeFormat = value => {
    let theTime = parseInt(value) // 需要转换的时间秒
    let theTime1 = 0 //
    let theTime2 = 0 // 小时
    let theTime3 = 0 //
    if (theTime > 60) {
      theTime1 = parseInt(theTime / 60)
      theTime = parseInt(theTime % 60)
      if (theTime1 > 60) {
        theTime2 = parseInt(theTime1 / 60)
        theTime1 = parseInt(theTime1 % 60)
        if (theTime2 > 24) {
          //大于24小时
          theTime3 = parseInt(theTime2 / 24)
          theTime2 = parseInt(theTime2 % 24)
        }
      }
    }
    let result = ''
    if (theTime > 0) {
      result = '' + parseInt(theTime) + '秒'
    }
    if (theTime1 > 0) {
      result = '' + parseInt(theTime1) + '分' + result
    }
    if (theTime2 > 0) {
      result = '' + parseInt(theTime2) + '小时' + result
    }
    if (theTime3 > 0) {
      result = '' + parseInt(theTime3) + '天' + result
    }
    return result
  }
  
// 36000000 毫秒
// 36000 秒
// 600 分
// 10 小时
timeFormat(36000000 / 1000); // 10个小时
View Code

06)获取当前文件目录位置

/**
 * 在windows系统中获取当前文件目录位置
 * @param newFilename 新文件名字
 * @returns {string|string} 目录 或者 目录+文件地址
 */
function getWinDir(newFilename) {
  const pathName = window.document.location.pathname;
  let arr = pathName.split('/')
  let filename = arr[arr.length - 1]
  let pos = pathName.indexOf(filename)
  let dirName = pathName.substring(0, pos).substring(1)
  return newFilename ? dirName + newFilename : dirName;
}
View Code

 

 

 

 

JavaScript里不为人知的秘密(01)之常见使用

JavaScript里不为人知的秘密(02)之常见使用

posted on 2021-06-08 20:05  大飞_dafei  阅读(43)  评论(0编辑  收藏  举报