前端进阶~~~必备小技巧(一)

  •  数字分隔符

             为了提高数字的可读性,您可以使用下划线作为分隔符:

const numbers = 1_2_3_4_5
console.log(numbers) // 12345
  •   字符串转数字

        弱类型转换

const num = '234’
console.log(typeof +num)

        强制类型转换

const num = '234’
console.log(typeof Number(num))

        转换函数

const num = '234’
console.log(typeof parseFloat(num))
console.log(typeof parseInt(num)) 
  •  数字转字符串

    显示转换

const numa = 12345
console.log( typeof(numa.toString()))
console.log( typeof(String(numa))) 

    隐示转换

const numa = 12345
console.log( typeof(numa +''))
  •  数组中获取最小值/最大值

       使用 Math.min()Math.max() 结合扩展运算符来查找数组中的最小值或最大值

    const numbers = [6, 2, 4, 3, 9, 5];
    console.log(Math.max(...numbers)); // 9
    console.log(Math.min(...numbers)); // 2
  •  缩短数组

    可以设置 length 属性来缩短数组

    const numbers = [1, 2, 3, 4, 5] 
    numbers.length = 3;
    console.log(numbers); // [1, 2, 3]
  •  简写条件判断语句

    如果仅在判断条件为 true 时才执行函数,则可以使用 && 简写

    // 普通写法 if (true) { doSomething(); }
    // 简写 true && doSomething();
  •  数组去重

    const numbers = [2, 5, 4, 4, 2, 6, 7, 3, 9];
    console.log([...new Set(numbers)]); // [2, 3, 4, 5, 6, 7, 9]
  •  从数组中过滤所有虚值

const myArray = [1, undefined, NaN, 2, null, '@163.com', true, 13, false];
console.log(myArray.filter(Boolean)); // [1, 2, "@163.com", true, 13]
  •   includes

const java= 'JavaScript'; const Arr= ['HTML', 'CSS', 'JavaScript'];
// 普通写法
  if (java === 'JavaScript') { // do something }
// includes 写法
  if (Arr.includes(java)) { // do something }
  •  合并数组

        const arr1 = [1,2]

        const arr2 = [4,5]

        方法一  for循环
for(let i in arr2){
     arr1.push(arr2[i])
}
console.log(arr1)

    方法二

console.log(arr1.concat(arr2))

    方法三   

console.log([...arr1, ...arr2])

 


                      🚀  相信技术的力量 

                                         💖平安喜乐💖    

                                                             🌌  相信努力的你

 

                                                                        2021-12-27 14:10:14

  

 
posted @ 2021-12-27 14:17  Song0916  阅读(36)  评论(0编辑  收藏  举报