这些 JavaScript函数让你的工作更加 So Easy!

爱丽丝13
• 阅读 1173

作者: YoussefZidan
译者:前端小智
来源:dev

点赞再看,养成习惯

本文 GitHub https://github.com/qq44924588... 上已经收录,更多往期高赞文章的分类,也整理了很多我的文档,和教程资料。欢迎Star和完善,大家面试可以参照考点复习,希望我们一起有点东西。

最近开源了一个 Vue 组件,还不够完善,欢迎大家来一起完善它,也希望大家能给个 star 支持一下,谢谢各位了。

github 地址:https://github.com/qq44924588...

在本文中,分享一些我几乎在每个项目中都会用到的一些函数。

randomNumber()


获取指定区间的随机数。

**
 * 在最小值和最大值之间生成随机整数。
 * @param {number} min Min number
 * @param {number} max Max Number
 */
export const randomNumber = (min = 0, max = 1000) =>
  Math.ceil(min + Math.random() * (max - min));

// Example
console.log(randomNumber()); // 97 

capitalize()


将字符串的第一个字母变为大写。

/**
 * Capitalize Strings.
 * @param {string} s String that will be Capitalized
 */
export const capitalize = (s) => {
  if (typeof s !== "string") return "";
  return s.charAt(0).toUpperCase() + s.slice(1);
}

// Example
console.log(capitalize("cat")); // Cat

truncate();


这对于长字符串很有用,特别是在表内部。

/**
 * 截断字符串....
 * @param {string} 要截断的文本字符串
 * @param {number} 截断的长度
 */
export const truncate = (text, num = 10) => {
  if (text.length > num) {
    return `${text.substring(0, num - 3)}...`
  }
  return text;
}

// Example
console.log(truncate("this is some long string to be truncated"));  

// this is... 

toTop();


滚到到底部,可以通过 behavior 属性指定滚动速度状态。

/**
 * Scroll to top
 */
export const toTop = () => {
  window.scroll({ top: 0, left: 0, behavior: "smooth" });
}; 

softDeepClone()


这个方法是经常被用到的,因为有了它,我们可以深度克隆嵌套数组或对象。

不过,这个函数不能与new Date()NaNundefinedfunctionNumberInfinity等数据类型一起工作。

你想深度克隆上述数据类型,可以使用 lodash 中的 cloneDeep() 函数。

/**
 * Deep cloning inputs
 * @param {any} input Input
 */
export const softDeepClone= (input) => JSON.parse(JSON.stringify(input));

appendURLParams() & getURLParams()


快速添加和获取查询字符串的方法,我通常使用它们将分页元数据存储到url

/**
 * Appen query string and return the value in a query string format.
 * @param {string} key
 * @param {string} value
 */
export const appendURLParams = (key, value) => {
  const searchParams = new URLSearchParams(window.location.search).set(key, value);
  return searchParams.toString();
};

// example
console.log(appendURLParams("name", "youssef")) // name=youssef

/**
 * Get param name from URL.
 * @param {string} name
 */
export const getURLParams = (name) => new URLSearchParams(window.location.search).get(name);

// Example
console.log(getURLParams(id)) // 5

getInnerHTML()


每当服务器返回一串HTML元素时,我都会使用它。

/**
 * 获取HTML字符串的内部Text
 * @param {string} str A string of HTML
 */
export const getInnerHTML = (str) => str.replace(/(<([^>]+)>)/gi, "");

scrollToHide()


上滚动以显示HTML元素,向下滚动以将其隐藏。

 /**
 * 下滚动时隐藏HTML元素。
 * @param {string} 元素的 id
 * @param {string} distance in px ex: "100px"
 */
export const scrollToHide = (id, distance) => {
  let prevScrollpos = window.pageYOffset;
  window.onscroll = () => {
    const currentScrollPos = window.pageYOffset;
    if (prevScrollpos > currentScrollPos) {
      document.getElementById(id).style.transform = `translateY(${distance})`;
    } else {
      document.getElementById(id).style.transform = `translateY(-${distance})`;
    }
    prevScrollpos = currentScrollPos;
  };
};

humanFileSize ()


传入字节为单位的文件,返回我们日常所熟悉的单位。

/**
 * Converting Bytes to Readable Human File Sizes.
 * @param {number} bytes Bytes in Number
 */
export const humanFileSize = (bytes) => {
  let BYTES = bytes;
  const thresh = 1024;

  if (Math.abs(BYTES) < thresh) {
    return `${BYTES} B`;
  }

  const units = ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

  let u = -1;
  const r = 10 ** 1;

  do {
    BYTES /= thresh;
    u += 1;
  } while (Math.round(Math.abs(BYTES) * r) / r >= thresh && u < units.length - 1);

  return `${BYTES.toFixed(1)} ${units[u]}`;
};

// Example
console.log(humanFileSize(456465465)); // 456.5 MB

getTimes()


你是否有一个DDL,它每n分钟显示一天的时间?用这个函数。

/**
 * Getting an Array of Times + "AM" or "PM".
 * @param {number} minutesInterval
 * @param {number} startTime 
 */
export const getTimes = (minutesInterval = 15, startTime = 60) => {
  const times = []; // time array
  const x = minutesInterval; // minutes interval
  let tt = startTime; // start time
  const ap = ["AM", "PM"]; // AM-PM

  // loop to increment the time and push results in array
  for (let i = 0; tt < 24 * 60; i += 1) {
    const hh = Math.floor(tt / 60); // getting hours of day in 0-24 format
    const mm = tt % 60; // getting minutes of the hour in 0-55 format
    times[i] = `${`${hh === 12 ? 12 : hh % 12}`.slice(-2)}:${`0${mm}`.slice(-2)} ${
      ap[Math.floor(hh / 12)]
    }`; // pushing data in array in [00:00 - 12:00 AM/PM format]
    tt += x;
  }
  return times;
};

// Example
console.log(getTimes());
/* [
    "1:00 AM",
    "1:15 AM",
    "1:30 AM",
    "1:45 AM",
    "2:00 AM",
    "2:15 AM",
    "2:30 AM",
    // ....
    ]
*/ 

setLocalItem() & getLocalItem()

LocalStorage 具有过期时间。

/**
 * Caching values with expiry date to the LocalHost.
 * @param {string} key Local Storage Key
 * @param {any} value Local Storage Value
 * @param {number} ttl Time to live (Expiry Date in MS)
 */
export const setLocalItem = (key, value, ttl = duration.month) => {
  const now = new Date();
  // `item` is an object which contains the original value
  // as well as the time when it's supposed to expire
  const item = {
    value,
    expiry: now.getTime() + ttl,
  };
  localStorage.setItem(key, JSON.stringify(item));
};

/**
 * Getting values with expiry date from LocalHost that stored with `setLocalItem`.
 * @param {string} key Local Storage Key
 */
export const getLocalItem = (key) => {
  const itemStr = localStorage.getItem(key);
  // if the item doesn't exist, return null
  if (!itemStr) {
    return null;
  }
  const item = JSON.parse(itemStr);
  const now = new Date();
  // compare the expiry time of the item with the current time
  if (now.getTime() > item.expiry) {
    // If the item is expired, delete the item from storage
    // and return null
    localStorage.removeItem(key);
    return null;
  }
  return item.value;
}; 

formatNumber()

 /**
 * Format numbers with separators.
 * @param {number} num
 */
export const formatNumber = (num) => num.toLocaleString();

// Example
console.log(formatNumber(78899985)); // 78,899,985

我们还可以添加其他选项来获取其他数字格式,如货币、距离、权重等。

export const toEGPCurrency = (num) =>
  num.toLocaleString("ar-EG", { style: "currency", currency: "EGP" });

export const toUSDCurrency = (num) =>
  num.toLocaleString("en-US", { style: "currency", currency: "USD" });

console.log(toUSDCurrency(78899985)); // $78,899,985.00
console.log(toEGPCurrency(78899985)); // ٧٨٬٨٩٩٬٩٨٥٫٠٠ ج.م.

toFormData()

每当我需要向服务器发送文件时,我就使用这个函数。

/**
 * Convert Objects to Form Data Format.
 * @param {object} obj
 */
export const toFormData = (obj) => {
  const formBody = new FormData();
  Object.keys(obj).forEach((key) => {
    formBody.append(key, obj[key])
  })

  return formBody;
}

getScreenWidth()

获取一个表示屏幕宽度的字符串。

/**
 * Detect screen width and returns a string representing the width of the screen.
 */
export const getScreenWidth = () => {
  const screenWidth = window.screen.width;
  if (screenWidth <= 425) return "mobile";
  if (screenWidth <= 768) return "tablet";
  if (screenWidth <= 1024) return "laptopSm";
  if (screenWidth <= 1440) return "laptopLg";
  if (screenWidth <= 2560) return "HD";
  return screenWidth;
}; 

检查数组中的每个元素是否存在于另一个数组中。

export const containsAll = (baseArr, arr) => {
  let all = false;

  for (let i = 0; i < arr.length; i += 1) {
    if (baseArr.includes(arr[i])) {
      all = true;
    } else {
      all = false;
      return all;
    }
  }

  return all;
};

你还有使用其他有用的函数吗?在评论里分享一下怎么样?

完~,我是小智,我要去刷碗去了。


代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug

原文:https://dev.to/youssefzidan/j...

交流

文章每周持续更新,可以微信搜索「 大迁世界 」第一时间阅读和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 已经收录,整理了很多我的文档,欢迎Star和完善,大家面试可以参照考点复习,另外关注公众号,后台回复福利,即可看到福利,你懂的。

这些 JavaScript函数让你的工作更加 So Easy!

本文转自 https://segmentfault.com/a/1190000039182225,如有侵权,请联系删除。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
Stella981 Stella981
2年前
2021 最顶级 React 组件库推荐
点上方蓝字关注公众号「前端从进阶到入院」作者丨MaxRozen译者丨王强策划丨小智AntDesign!(https://oscimg.oschina.net/oscnet/a85c35f23bd04e5da6a1e5e68a24119b.png)项目链接:AntDesignh
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
可莉 可莉
2年前
2021 最顶级 React 组件库推荐
点上方蓝字关注公众号「前端从进阶到入院」作者丨MaxRozen译者丨王强策划丨小智AntDesign!(https://oscimg.oschina.net/oscnet/a85c35f23bd04e5da6a1e5e68a24119b.png)项目链接:AntDesignh
可莉 可莉
2年前
10个很棒的 JavaScript 字符串技巧
作者:Kai译者:前端小智来源:dev点赞再看,微信搜索【大迁世界】关注这个没有大厂背景,但有着一股向上积极心态人。本文GitHubhttps://github.com/qq44924588...(https://www.oschina.net/action/GoToLink?urlhttps%
Wesley13 Wesley13
2年前
35岁是技术人的天花板吗?
35岁是技术人的天花板吗?我非常不认同“35岁现象”,人类没有那么脆弱,人类的智力不会说是35岁之后就停止发展,更不是说35岁之后就没有机会了。马云35岁还在教书,任正非35岁还在工厂上班。为什么技术人员到35岁就应该退役了呢?所以35岁根本就不是一个问题,我今年已经37岁了,我发现我才刚刚找到自己的节奏,刚刚上路。
可莉 可莉
2年前
13 个 JavaScript 数组精简技巧
作者:Duomly译者:前端小智来源:dev.to点赞再看,微信搜索【大迁世界】关注这个没有大厂背景,但有着一股向上积极心态人。本文GitHubhttps://github.com/qq44924588...(https://www.oschina.net/action/GoToL
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这