侧边栏壁纸
博主头像
M酷博主等级

一帆风顺 ⛵️⛵️⛵️

  • 累计撰写 45 篇文章
  • 累计创建 40 个标签
  • 累计收到 456 条评论

目 录CONTENT

文章目录

【收藏】一波实用的JS小技巧

M酷
2021-01-19 / 0 评论 / 0 点赞 / 1,198 阅读 / 3,418 字 / 正在检测是否收录...
广告 广告

1、生成不重复的随机数

思路:定义一个很多数字的数组,每次取出一项,然后打乱数组,再取,永远不重复。

const count = 3000;
const originalArray = []; //原数组
//给原数组originalArray赋值
for (let i = 0; i < count; i++) {
    originalArray[i] = i + 1;
}
originalArray.sort(() => 0.5 - Math.random());
for (let i = 0; i < count; i++) {
    document.write(originalArray[i] + " , ");
}

2、生成字母和数字组成的随机字符串

思路:实用toString方法的参数,传入36的时候刚好可以返回包含字母和数字的字符串。

Math.random().toString(36);
function generateRandomAlphaNum(len) {
    var rdmString = "";
    for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
    return rdmString.substr(0, len);
}

3、将类数组转为普通数组

思路:可以使用ES6的Array.from()或者Array.prototype.slice.call()实现

var arrLike = { 0: 1, 2: 2, 3: 3, length: 3 };
[...arrLike]; // [1,2,3]
Array.from(arrLike); // [1,2,3]
Array.apply(null, arrLike); // [1,2,3]
[].slice.call(arrLike); // [1,2,3]

4、打乱一个数组

主要使用 Math.random() 和数组的 sort 方法实现。

let numbers = [1, 2, 3, 4, 5, 6, -8];
numbers = numbers.sort(() => Math.random() - 0.5});

5、取出一个数组中的最大值和最小值

主要使用 Math对象下的 max 和 min 方法实现。

const numbers = [1, 2, 3, 4, 5, 6, -8]; 
const max = Math.max.apply(Math, numbers); // 6
const min = Math.min.apply(Math, numbers); // -8

6、将一个数组追加到另一个数组中

思路:可以直接使用concat来合并数组,但使用push会更快,因为concat会创建一个新数组。

const array1 = [12 , "foo" , {name: "Chin"} , -20];
const array2 = ["Joy" , 555 , 100];
[].push.apply(array1, array2);
console.log(array1) // [12 , "foo" , {name: "Chin"} , -20, "Joy" , 555 , 100]

7、生成唯一的uuid

思路:可以使用URL对象的createObjectURL()方法配合Blob对象来实现。

function uuid() {
  const temp_url = URL.createObjectURL(new Blob());
  const uuid = temp_url.toString(); // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
  URL.revokeObjectURL(temp_url);
  return uuid.substr(uuid.lastIndexOf("/") + 1);
}

8、实现通过字符串 "a.b.c" 读取对象中的属性

可以通过while循环配合数组pop或shift,最终读取对应属性的值。

const obj = { a: { b: { c: 35355 } } };
const revealVal = (data, str) => {
  const arr = str.split(".");
  while (arr.length && (data = data[arr.shift()]));
  return data;
};
revealVal(obj, "a.b.c"); // 666

9、获取数组中最小值及其索引

可以先使用 Math.min 找到最小值,再用 findIndex() 找到对应的索引,但肯定还有更好的方法,先留个眼。

// @获取数据组中最小值及索引
const findMinData= data => {
    const min = Math.min(...data)
    const minIndex = data.findIndex(c => c === min)
    return {
        min,
        minIndex
    }
}
findMinData([1,3,2,8,0]); // {0, 4}

10、获取数组中数字的平均值

可以使用数组的 reduce 方式来实现求值。

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4); // 2.5

11、转换摄氏度和华氏度

直接使用对应的转换关系计算即可。

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
celsiusToFahrenheit(15); // 59
fahrenheitToCelsius(59); // 15

12、检查当前是否为苹果设备

直接使用对应的转换关系计算即可。

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);

13、检查浏览器是否支持触摸事件

直接使用对应的转换关系计算即可。

const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}

14、保留小数位

使用双位运算符和 Math.pow() 方法实现。

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
toFixed(36.198726354, 1); // 36.1
toFixed(36.198726354, 2); // 36.19
toFixed(36.198726354, 3); // 36.198

15、检查是否为偶数

使用按位与或取模运算符均可判断。

const isEven = (num) => num & 1 === 0;
// or
const isEven = (num) => num % 2 === 0;

isEven (2); // true
isEven (3); // false

16、检查当前 Tab 页是否在前台

可以直接用 document 对象中的静态属性 hidden 获取。

const isTabView = document.hidden;
console.log(isTabView ); // true

17、检查日期是否为工作日

通过日期对象的 getDay() 方法获取星期然后和6做取模操作,看是否等于0。

const isWorkday = (date) => date.getDay() % 6 !== 0;
console.log(isWorkday(new Date(2021, 0, 11)));

18、首字母大写

通过正则表达式配合replace快速搞定。更多方法

const toCapitalize = (str) => str.toLowerCase().replace(/(^|\s)[a-z]{1}/g,match=>match.toUpperCase());
toCapitalize('i Am a boy'); // I AM A Boy
0
广告 广告

评论区