栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

js技巧 1-2

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

js技巧 1-2

一、数组处理

1.从数组中移除重复
//该方法用于移除数组中的重复项:

const removeDuplicates = (arr) => [...new Set(arr)];

console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));

2.判断数组是否为空
//该方法用于判断一个数组是否为空数组,它将返回一个布尔值:

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]);  // true

3. 合并两个数组
//两种方式合并两个数组

const merge = (a, b) => a.concat(b);

const merge = (a, b) => [...a, ...b];

4. 打乱数组(利用内置Math.random()方法)
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
    return Math.random() - 0.5;
});
// 输出
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]
5.三元运算符很酷
//您可以避免使用三元运算符嵌套条件 if…elseif…elseif。


function Fever(temp) {
    return temp > 97 ? 'Visit Doctor!'
      : temp < 97 ? 'Go Out and Play!!'
      : temp === 97 ? 'Take Some Rest!';
}

// 输出
Fever(97): "Take Some Rest!" 
Fever(100): "Visit Doctor!"
6. 对字符串、数字或对象数组进行排序
//1.排序字符串数组
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// 输出 ["Joe", "Kapil", "Musk", "Steve"]

stringArr.reverse();
// 输出["Steve", "Musk", "Kapil", "Joe"]



//2.排序数字数组
const array  = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// 输出[1, 5, 10, 25, 40, 100]

array.sort((a,b) => b-a);
// 输出[100, 40, 25, 10, 5, 1]


//3.排序对象数组
const objectArr = [ 
    { first_name: 'Lazslo', last_name: 'Jamf'     },
    { first_name: 'Pig',    last_name: 'Bodine'   },
    { first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// 输出 [{…}, {…}, {…}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3

7. 从数组中过滤出虚假值
//Falsy值喜欢0,undefined,null,false,"",''可以很容易地通过以下方法省略
const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// 输出 [3, 6, 7]
8. 创建计数器对象或映射
//大多数情况下,需要通过创建计数器对象或映射来解决问题,该对象或映射将变量作为键进行跟踪,并将其频率/出现次数作为值进行跟踪。

let string = 'kapilalipak';
const table={}; 
for(let char of string) {
  table[char]=table[char]+1 || 1;
}
// 输出
{k: 2, a: 3, p: 2, i: 2, l: 2}

const countMap = new Map();
  for (let i = 0; i < string.length; i++) {
    if (countMap.has(string[i])) {
      countMap.set(string[i], countMap.get(string[i]) + 1);
    } else {
      countMap.set(string[i], 1);
    }
  }
// 输出
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}

9.获取变量的类型
//该方法用于获取一个变量的类型:

const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();

trueTypeOf('');     // string
trueTypeOf(0);      // number
trueTypeOf();       // undefined
trueTypeOf(null);   // null
trueTypeOf({});     // object
trueTypeOf([]);     // array
trueTypeOf(0);      // number
trueTypeOf(() => {});  // function
复制代码
10. 检测对象是否为空
//该方法用于检测一个JavaScript对象是否为空:
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
复制代码

二、数字操作 1.获得一数组的平均数
const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4, 5);   // 3

2. 获取两个整数之间的随机整数
//该方法用于获取两个整数之间的随机整数


const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

random(1, 50);
复制代码
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

random(1, 50);

3.指定位数四舍五入

//该方法用于将一个数字按照指定位进行四舍五入

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

round(1.005, 2) //1.01
round(1.555, 2) //1.56

三、颜色操作

#1. 将RGB转化为十六进制
//该方法可以将一个RGB的颜色值转化为16进制值:

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(255, 255, 255);  // '#ffffff'

#2. 获取随机十六进制颜色
//该方法用于获取一个随机的十六进制颜色值:

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

randomHex();

四、浏览器操作

#1. 复制内容到剪切板
//该方法使用 navigator.clipboard.writeText 来实现将文本复制到剪贴板:

const copyToClipboard = (text) => navigator.clipboard.writeText(text);

copyToClipboard("Hello World");

2. 清除所有cookie
//该方法可以通过使用 document.cookie 来访问 cookie 并清除存储在网页中的所有 cookie:

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));

3. 获取选中的文本
//该方法通过内置的 getSelection 属性获取用户选择的文本:

const getSelectedText = () => window.getSelection().toString();

getSelectedText();


4. 检测是否是黑暗模式
//该方法用于检测当前的环境是否是黑暗模式,它是一个布尔值:

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode)

5. 滚动到页面顶部
//该方法用于在页面中返回顶部:


const goToTop = () => window.scrollTo(0, 0);

goToTop();

6. 判断当前标签页是否激活
//该方法用于检测当前标签页是否已经激活:
const isTabInView = () => !document.hidden;

7. 判断当前是否是苹果设备
//该方法用于检测当前的设备是否是苹果的设备:

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

8. 是否滚动到页面底部
//该方法用于判断页面是否已经底部:
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;

9. 重定向到一个URL
//该方法用于重定向到一个新的URL:

const redirect = url => location.href = url
redirect("https://www.google.com/")

10. 打开浏览器打印框
//该方法用于打开浏览器的打印框:
const showPrintDialog = () => window.print()

暑期编程PK赛 得CSDN机械键盘等精美礼品!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1017491.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号