zoukankan      html  css  js  c++  java
  • Javascript 有用的奇淫技巧

    Javascript 有用的奇淫技巧

    es6去重

    const array = [1, 1, 2, 3, 5, 5, 1]
    const uniqueArray = [...new Set(array)];
    console.log(uniqueArray); // [1, 2, 3, 5]
    

    此技巧适用于包含基本类型的数组:undefined,null,boolean,string和number。 (如果你有一个包含对象,函数或其他数组的数组,你需要一个不同的方法!)

    快速浮点数转整数

    如果希望将浮点数转换为整数,可以使用Math.floor()、Math.ceil()或Math.round()。但是还有一种更快的方法可以使用|(位或运算符)将浮点数截断为整数。

    console.log(23.9 | 0);  // 23
    console.log(-23.9 | 0); // -23
    

    删除最后一个数字

    按位或运算符还可以用于从整数的末尾删除任意数量的数字。这意味着我们不需要使用这样的代码来在类型之间进行转换。

    console.log(1553 / 10   | 0)  // 155
    console.log(1553 / 100  | 0)  // 15
    console.log(1553 / 1000 | 0)  // 1
    

    向下取整最快方式

    向下取整有很多方法, Math.floor, parseInt都可以, 不过两个非(~)运算符来取整是最方便的, 而且逻辑运算很快。还可以用~~再加1来向上取整。

    console.log(~~3.14) 	// 3
    console.log(~~-3.14) 	// -3
    console.log(~~Math.E)	// 2
    

    获取指定范围内均匀分布的随机数

    let x = Math.random() * (max - min) + min;
    

    最快生成[1,2,3, .... ,n] 的列表

    var arr = Array(10).fill(true).map((x, i) => i + 1);
    console.log(arr); 	// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    

    打乱列表

    利用sort方法快速排序的时候引入一个随机量

    const arr = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
    const newArr = arr.sort(() => Math.random() - 0.5);
    console.log(arr); 	// [458, 5, -215, 120, 400, 228, -85411, 122205]
    
  • 相关阅读:
    164 Maximum Gap 最大间距
    162 Find Peak Element 寻找峰值
    160 Intersection of Two Linked Lists 相交链表
    155 Min Stack 最小栈
    154 Find Minimum in Rotated Sorted Array II
    153 Find Minimum in Rotated Sorted Array 旋转数组的最小值
    152 Maximum Product Subarray 乘积最大子序列
    151 Reverse Words in a String 翻转字符串里的单词
    bzoj3994: [SDOI2015]约数个数和
    bzoj 4590: [Shoi2015]自动刷题机
  • 原文地址:https://www.cnblogs.com/jone-chen/p/12176747.html
Copyright © 2011-2022 走看看