10 个「有用」JavaScript 代码片段

3,466 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第16天,点击查看活动详情


降低阅读负担,启发创作心智,轻松学习 JavaScript 技巧,日拱一卒,jym,冲~

take-it-easy-relax.gif

注:本篇可能更适合 JS 新手食用,大佬请绕道🤝

类数组转数组

什么是类数组?

我们最常见的类数组比如函数的参数 arguments

const fn = function(){
    console.log(arguments)
}

fn("a1","a2","a3")

打印结果:

image.png

类数组的属性为数字、并且还有 length 属性,主要是为了保证 arguments[i] 和 arguments.length 都能拿到值。

将类数组转化为数组我们通常用 call 方法:

Array.prototype.slice.call(arguments);

其实也可以用 ... 扩展符实现类数组转数组:

[...arguments]

精简 console.log

全局这样声明,后面再使用 console.log 打印值就方便多啦:

const c = console.log.bind(document) 

c(222) // 222
c("hello world") // hello world

对象动态属性

声明对象时,如果属性是动态的,可以这样声明:

const dynamic = 'color';
var item = {
    brand: 'Ford',
    [dynamic]: 'Blue'
}
console.log(item); 
// { brand: "Ford", color: "Blue" }

获取链接参数

我们都知道 window.location.search 可以获取 url 中 ““?” 问号后面的参数:

window.location.search

然后我们可以再通过 new URLSearchParams(location.search).get('type') 方法获取具体某一个参数的值

let type = new URLSearchParams(location.search).get('type');

比如:

image.png

好用!!

删除数组元素

很多同学会用 delete 删除数组的值,这样做数组长度并不会发生变化,并且取值会是 undefined

image.png

推荐使用 splice 来删除数组元素

const array = ["a", "b", "c", "d"] 
array.splice(0, 2) // ["a", "b"]

对象判空

对象判空小技巧,使用 Object.keys({})

Object.keys({}).length  // 0
Object.keys({key: 1}).length  // 1

推荐switch case

推荐使用 switch case 而不是 if...else if...

if (1 == month) {days = 31;}
else if (2 == month) {days = IsLeapYear(year) ? 29 : 28;}
else if (3 == month) {days = 31;}
else if (4 == month) {days = 30;} 
else if (5 == month) {days = 31;} 
else if (6 == month) {days = 30;} 
else if (7 == month) {days = 31;} 
else if (8 == month) {days = 31;} 
else if (9 == month) {days = 30;} 
else if (10 == month) {days = 31;} 
else if (11 == month) {days = 30;} 
else if (12 == month) {days = 31;}
switch(month) {
        case 1: days = 31; break;
        case 2: days = IsLeapYear(year) ? 29 : 28; break;
        case 3: days = 31; break;
        case 4: days = 30; break;
        case 5: days = 31; break;
        case 6: days = 30; break;
        case 7: days = 31; break;
        case 8: days = 31; break;
        case 9: days = 30; break;
        case 10: days = 31; break;
        case 11: days = 30; break;
        case 12: days = 31; break;
        default: break;
}

也更推荐用 map 的方法:

let getDays={
    1:31,
    2:IsLeapYear(year) ? 29 : 28,
    3:31,
    ...
}

getDays[month]

获取数组最后一项

获取数组最后一项有更简单的写法:arr.slice(-1)

const arr = [1, 2, 3, 4, 5];
arr[arr.length - 1]  // 5
arr.slice(-1) // [5]

slice 也并不会修改原来的数组: image.png

转换成布尔值

类型转换,!! 两个感叹号可以将变量转换为布尔值。之前就有看到有人问 !! 双感叹是干啥的,这下知道了吧~

!!undefined // false
!!"996"     // true
!!null      // false
!!NaN       // false

用对象传参

把参数包装成一个对象再传,否则谁能读懂这种没头没尾的且要求顺序的参数的意义?

function getItem(price, quantity, name, description) {}
getItem(15, undefined, 'bananas', 'fruit')
function getItem(args) {
    const {price, quantity, name, description} = args
}
getItem({
    name: 'bananas',
    price: 10,
    quantity: 1, 
    description: 'fruit'
})

OK,以上便是本篇分享。点赞关注评论,为好文助力👍

我是掘金安东尼 🤠 100 万人气前端技术博主 💥 INFP 写作人格坚持 1000 日更文 ✍ 关注我,安东尼陪你一起度过漫长编程岁月 🌏