javascript的小技巧

1.全部替换

我们知道 string.replace() 函数仅替换第一次出现的情况。
可以通过在正则表达式的末尾添加 /g来替换所有出现的内容。

   var example = "potato potato";
    console.log(example.replace(/pot/, "tom")); 
    // "tomato potato"
    console.log(example.replace(/pot/g, "tom")); 
    // "tomato tomato”

2.数组去重

通过使用set对象和展开运算符

    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.将数字转换为字符串

我们只需要使用带空引号的串联运算符。

	var converted_number = 5 + "";
    console.log(converted_number);
    // 5
    console.log(typeof converted_number); 
    // string

4.字符串转换为数字

我们需要的只是 + 运算符。
请注意它仅适用于“字符串数字”。

 var the_string = "123";
    console.log(+the_string);
    // 123

    var the_string = "hello";
    console.log(+the_string);
    // NaN

5.随机排列数组中的元素

 	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.展开多维数组

	var entries = [1, [2, 5], [6, 7], 9];    
    var flat_entries = [].concat(...entries); 
    // [1, 2, 5, 6, 7, 9]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值