QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 2169|回复: 0

[HTML/CSS/JS] 9 个好用的 JavaScript 小技巧

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1322 小时
   最后登录 : 2025-11-29

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2020-12-12 11:02:29 | 显示全部楼层 |阅读模式
1. 全部替换
* T. N4 P5 ~: [+ S! K7 j$ e$ g       我们都知道 string.Replace() 函数仅能替换掉第一个匹配项。你可以通过在正则表达式的末尾添加 /g 来替换所有出现的内容。
( G0 g3 C2 ?% {/ x% A! P8 l1 s- s
var example = "potato potato";
console.log(example.replace(/pot/, "tom")); 
// "tomato potato"
console.log(example.replace(/pot/g, "tom")); 
// "tomato tomato"
2. 提取唯一值7 Y5 ^2 R0 w8 L3 |" p
       通过使用 Set 对象和 ... 运算符能够使用唯一值创建一个新数组。
! R7 q+ B$ w6 i* Y+ [  V" M) n# g
var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]
3. 将数字转换为字符串! ^6 h0 B' ^8 y8 T! x
       只需要用 + 运算符带和一个空字符串即可。6 L& }% d! u' f8 H
var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number); 
// string
4.将字符串转换为数字
# F: b1 m+ X. n2 F" Q/ R: ^' Y1 C       只需要用 + 运算符即可。但是要注意:它仅适用于“字符串数字”。$ Z8 z1 D. `* h- R9 c# r
the_string = "123";
console.log(+the_string);
// 123the_string = "hello";
console.log(+the_string);
// NaN
5. 随机排列数组中的元素9 O/ E, t+ O+ A/ }/ A8 \
       这样最适合洗牌了:4 t3 L, B4 Y. u: o  |8 N
var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(my_list.sort(function() {
    return Math.random() - 0.5
})); 
// [4, 8, 2, 9, 1, 3, 6, 5, 7]
6.展平多维数组
& B5 j4 l" W) M8 f: s       只需使用 ... 运算符。
" d% T' Y" j5 V# P. c6 G  w
var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries); 
// [1, 2, 5, 6, 7, 9]
7. 条件短路/ |* A4 X1 D; G8 k2 X
       只需要举个例子就明白了:' G& x5 A: k+ P' u6 o1 [
if (available) {
    addToCart();
}
      通过简单地使用变量和函数来简化代码:
( }. \4 x! `& N1 p8 T' W$ x
available && addToCart()
8. 动态属性名
4 R% Z  c8 W1 }/ q7 u' ^0 S       一直以来,我以为必须先声明一个对象,然后才能分配动态属性,但是...
4 g' g- x6 L5 f6 V! s/ W# t4 ]
const dynamic = 'flavour';
var item = {
    name: 'Coke',
    [dynamic]: 'Cherry'
}
console.log(item); 
// { name: "Coke", flavour: "Cherry" }
9. 用 length 调整货清空数组$ x% i2 ?' q4 }# C& |5 K8 c
       如果要调整数组的大小:: Y% l6 U& V0 n9 A0 t8 w
var entries = [1, 2, 3, 4, 5, 6, 7];  
console.log(entries.length); 
// 7  
entries.length = 4;  
console.log(entries.length); 
// 4  
console.log(entries); 
// [1, 2, 3, 4]
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2025-12-17 13:52

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表