JavaScript小技巧

JavaScript小技巧

现代 JavaScript 教程:https://zh.javascript.info

JavaScript小技巧:

声明多个变量
// 常规写法
let a;
let b = 1;
let c = true;

// 简写
let a, b = 1, c = true;
给多个变量赋值
// 常规写法
let a, b, c;
a = "a";
b = 1;
c = true;

// 简写
let [a, b, c] = ["a", 1, true];
交换变量的值
let str1 = "aaa";
let str2 = "bbb";

[str1, str2] = [str2, str1]
console.log(str1) // "bbb"
console.log(str2) // "aaa"
数字和字符串相互转换
const num = 99;
// 数字转字符串
console.log(num + '') // "99"

const str = '99';
// 字符串转数字
console.log(+str) // 99  
可选链操作符 ?.
  • 可选链操作符 ( ?. ) 允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空 (nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined
const user = {
  info: {
    name: "廊坊吴彦祖"
  }
};

console.log(user.info?.name) // "廊坊吴彦祖"
console.log(user.data?.name) // undefined
console.log(user.data.name) // TypeError: Cannot read properties of undefined (reading 'name')
空值合并操作符 ??
  • 空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数
console.log(null ?? "廊坊吴彦祖") // "廊坊吴彦祖"
console.log(undefined ?? "廊坊吴彦祖") // "廊坊吴彦祖"
console.log("廊坊吴彦祖" ?? "??") // "廊坊吴彦祖"
console.log(0 ?? 9) // 0
使用&&代替if判断为真
// if判断
if(true) {
  console.log("true") // "true"
}

// 使用&&代替if判断
true && console.log("true") // "true"
获取数组最后一位
const array  = [2, 1, 3, 5, 3, 6, 11];

// 通过.length获取数组最后一位
console.log(array[array.length - 1]) // 11

// 通过.at获取数组最后一位
console.log(array.at(-1)) // 11
打乱数组
const array  = [2, 1, 3, 5, 3, 6, 11];

// 通过sort方法和Math.random()打乱数组
array.sort(() => {
    return Math.random() - 0.5;
});
console.log(array) // [6, 2, 5, 1, 3, 3, 11]
获取对象的键和值数组
let obj = {a: 1, b: 2, c: 3}

// 通过Object.keys()获取obj对象键数组
console.log(Object.keys(obj)) // ["a", "b", "c"]
            
// 通过Object.values()获取obj对象值数组
console.log(Object.values(obj)) // [1, 2, 3]
Object.freeze() 冻结对象
  • Object.freeze() 方法可以冻结一个对象。一个被冻结的对象再也不能被修改;冻结了一个对象则不能向这个对象添加新的属性,不能删除已有属性,不能修改该对象已有属性的可枚举性、可配置性、可写性,以及不能修改已有属性的值。此外,冻结一个对象后该对象的原型也不能被修改。freeze() 返回和传入的参数相同的对象
let obj = {a: 1, b: 2}

// 将obj对象进行冻结
Object.freeze(obj)

// 无法给obj对象添加属性
obj.c = 3
console.log(obj) // {a: 1, b: 2}

// 无法删除obj对象某一个属性
delete obj.a
console.log(obj) // {a: 1, b: 2}
禁止输入框键入键盘某个键
<input type="text" placeholder="" onKeydown="keydown"/>
// 通过onKeydown事件判断
keydown(e) {
  // 不能输入'-'
  if (e.key === '-') {
    e.returnValue = false;
  }
},
区分IE和非IE浏览器
if (!+[1]) {
  // IE浏览器
} else {
  // 非IE浏览器
}
滚动到页面顶部
window.scrollTo(0, 0)
获取时间的毫秒数
// +new Date()相当于new Date().getTime()
console.log(+new Date("2022-07-12")) // 1657584000000
console.log(new Date("2022-07-12").getTime()) // 1657584000000
获取两个日期之间的天数
const getDay = (startDate, endDate) => Math.ceil(Math.abs(startDate.getTime() - endDate.getTime()) / 86400000)
    
const day = getDay(new Date("2022-7-12"), new Date("2021-7-12"))
console.log(day) // 365
利用reduce求数组总和、最小值和最大值
const array  = [2, 1, 3, 5, 3, 6, 11];

// 求总和
const total = array.reduce((a, b) => a+b);
console.log(total) // 31

// 求最小值(等同于Math.min())
const min = array.reduce((a, b) => a<b ? a : b);
console.log(min) // 1
console.log(Math.min(...array)) // 1

// 求最大值(等同于Math.max())
const max = array.reduce((a, b) => a>b ? a : b);
console.log(max) // 11
console.log(Math.max(...array)) // 11
数组去重
const array  = [1, 4, 4, 6, 8, 9, 11, 9, 'a', 'a'];

// 通过filter和indexOf方法
const ary1 = array.filter((item, index, arr) => arr.indexOf(item) === index);
console.log(ary1) // [1, 4, 6, 8, 9, 11, "a"]

// 通过Set
const ary2 = [...new Set(array)];
console.log(ary2) // [1, 4, 6, 8, 9, 11, "a"]
获取两个数组的交集
const ary1 = [1, 4, 6, 7, 9];
const ary2 = [ 8, 6, 11, 9];

// 通过filter和indexOf方法
const getIntersection = (ary1, ary2) => ary1.filter(item => ary2.indexOf(item) > -1);
console.log(getIntersection(ary1, ary2)) // [6, 9]
获取两个数组的并集
const ary1 = [1, 4, 6, 7, 9];
const ary2 = [ 8, 6, 11, 9];

// 通过concat和includes方法
const getUnion = (ary1, ary2) => ary1.concat(ary2.filter(item => !ary1.includes(item)))
console.log(getUnion(ary1, ary2)) // [1, 4, 6, 7, 9, 8, 11]
es6扩展运算符合并数组和对象
const ary1 = [1, 4, 4, 6];
const ary2 = [ 8, 9, 11, 9];

// 合并数组
const ary = [...ary1, ...ary2];
console.log(ary) // [1, 4, 4, 6, 8, 9, 11, 9]

const obj1 = {a: 1, b: 2};
const obj2 = {a: 3, c: 4};

// 合并对象
const obj = {...obj1, ...obj2};
console.log(obj) // {a: 3, b: 2, c: 4}
金额显示增加千位符
const getThousandsNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

const money = getThousandsNum(100000000);
console.log(money) // "100,000,000"
五星好评效果
const getStartScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);

console.log(getStartScore(3)) // "★★★☆☆"
console.log(getStartScore(5)) // "★★★★★"
通过length清空和截取数组
const array  = [2, 1, 3, 5, 3, 6, 11];

// 通过设置length来截取指定长度数组
array.length = 3;
console.log(array) // [2, 1, 3]

// 通过设置length为0来清空数组
array.length = 0;
console.log(array) // []
字符串首字母大写
const getUpperCaseStr = str => str.charAt(0).toUpperCase() + str.slice(1);

const upperCaseStr = getUpperCaseStr("beijing");
console.log(upperCaseStr) // "Beijing"
翻转字符串
const getReverseStr = str => str.split('').reverse().join('');

const reverseStr = getReverseStr("beijing");
console.log(reverseStr) // "gnijieb"
去除字符串中的空格
// 去除首尾的空格
const getTrimStr = str => str.replace(/(^\s*)|(\s*$)/g, "");
console.log(getTrimStr(" bei jing ")) // "bei jing"// 去除全部空格
const getTrimAllStr = str => str.replace(/\s+/g,"");
console.log(getTrimAllStr(" bei jing ")) // "beijing"
获取随机字符串
const str = Math.random().toString(36).substring(2);

console.log(str) // "fropwvrg7ke"
获取随机16进制颜色
const color = "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");

console.log(color) // "#71e3fd"
rgb颜色转16进制颜色
const getRgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

console.log(getRgbToHex(255, 255 ,255)) // "#ffffff"
判断数据类型
  • 默认情况下,toString() 方法被每个 Object 对象继承,如果此方法在自定义对象中未被覆盖, toString() 方法会返回一个 “[object xxxx]” 的字符串(xxxx 为数据具体类型)。可以通过 toString() 来获取每个对象的类型,为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 call() 或者 apply() 的形式来调用,传递要检查的对象作为第一个参数,即 Object.prototype.toString.call()(或者 Object.prototype.toString.apply())
const getTypeOf = val => Object.prototype.toString.call(val).slice(8, -1).toLowerCase();

console.log(getTypeOf(1)) // "number"
console.log(getTypeOf("廊坊吴彦祖")) // "string"
console.log(getTypeOf(true)) // "boolean"
console.log(getTypeOf(undefined)) // "undefined"
console.log(getTypeOf(function() {})) // "function"
console.log(getTypeOf(null)) // "null"
console.log(getTypeOf([1,2,3])) // "array"
console.log(getTypeOf({a: 'b'})) // "object"
for循环简写
  • for…of 语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
  • for…in 语句以任意顺序迭代一个对象的除 Symbol 以外的可枚举属性,包括继承的可枚举属性
const array  = [2, 1, 3, 5, 3, 6, 11];

// for循环
for (let i = 0; i < array.length; i++) {
  console.log(array[i]) // 2 1 3 5 3 6 11
}

// for...of获取数组每一项
for (let item of array) {
  console.log(item) // 2 1 3 5 3 6 11
}

// for...in获取数组索引
for (let index in array) {
  console.log(index) // "0" "1" "2" "3" "4" "5" "6"
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值