JavaScript 的10个你应该知道的小技巧

JavaScript 优化小技巧系列文章将在本号陆续发布,一起查漏补缺学个痛快!若您有遇到其它相关问题,非常欢迎在评论中留言讨论,达到帮助更多人的目的。若感本文对您有所帮助请点个赞吧!


1.波浪号的妙用(转为数字或小数取整)

var str = "123.123";
console.log(~~str);


//输出
123

2.用感叹号将非布尔值转换为布尔值

var str = "abc";
console.log(!str);


//输出
false

3.数字保留小数点后N位

var num = 10 / 3;
~~(num*10000)/10000;


//返回
3.3333

4.快速浮点数转整数

console.log(6.66 | 0);   // 6
console.log(-6.66 | 0);   // -6
console.log(~~6.66);   // 6
console.log(~~-6.66);   // -6

5.奇数和偶数

const value = 122;
if(value & 1) console.log("odd")
else console.log("even")
//even

6.距离过去到现在时间表示

const fromAgo = (date) => {
  const ms = Date.now() - date.getTime();
  const seconds = Math.round(ms / 1000);
  const minutes = Math.round(ms / 60000);
  const hours = Math.round(ms / 3600000);
  const days = Math.round(ms / 86400000);
  const months = Math.round(ms / 2592000000);
  const years = Math.round(ms / 31104000000);


  switch (true) {
    case seconds < 60:
      return `${seconds} second(s) ago"`;
    case minutes < 60:
      return `${minutes} minute(s) ago"`;
    case hours < 24:
      return `${hours} hour(s) ago"`;
    case days < 30:
      return `${days} day(s) ago`;
    case months < 12:
      return `${months} month(s) ago`;
    default:
      return `${years} year(s) ago`;
  }
};


const createdAt = new Date(2021, 0, 5);
fromAgo(createdAt); // 2 month(s) ago;

7.从路径获取参数

const getPathParams = (path, pathMap, serializer) => {
  path = path.split("/");
  pathMap = pathMap.split("/");
  return pathMap.reduce((acc, crr, i) => {
    if (crr[0] === ":") {
      const param = crr.substr(1);
      acc[param] = serializer && serializer[param]
        ? serializer[param](path[i])
        : path[i];
    }
    return acc;
  }, {});
};


getPathParams("/app/products/123", "/app/:page/:id");
// { page: 'products', id: '123' }


getPathParams("/items/2/id/8583212", "/items/:category/id/:id", {
  category: v => ['Car', 'Mobile', 'Home'][v],
  id: v => +v
});
// { category: 'Home', id: 8583212 }

8.判断值是否为整数

let num = 123
let numStr = "123"
console.log(Number.isInteger(num));      //true
console.log(Number.isInteger(numStr));   //false

9.去除字符串空格

//去除首尾空格
function trim(str){
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
trim('  hello world    '); //"hello world"


//去除所有空格
function trimAll(str){
    return str.replace(/\s+/g,"");
}
trimAll('   he ll o  wo  r ld    '); //"helloworld"

10.获取数组中的最后一个元素

let array = [1,3,5,7,9];
console.log(array.slice(-1)); //[9]

JavaScript 优化小技巧系列文章将在本号陆续发布,一起查漏补缺学个痛快!若您有遇到其它相关问题,非常欢迎在评论中留言讨论,达到帮助更多人的目的。若感本文对您有所帮助请点个赞吧!

贾佳

HFun 前端攻城狮

往期精彩:JavaScript的10个 小技巧

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值