JS常见的应用技巧

全部替换

我们知道 string.Replace() 函数只会替换第一个项目。

你可以在这个正则表达式的末尾添加 /g 来替换所有内容。

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

随机排列数组中的元素

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]

展开多维数组

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9]

短路条件

if (available) {
    addToCart();
}

只需使用变量和函数就能缩短它:

available && addToCart()

动态属性名称

const dynamic = 'flavour';
var item = {
    name: 'Coke',
    [dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" }

日志级别和语义方法

console.log("hello world")
console.warn("this is a warning")
console.error("this is an error")
console.info("this is info")
console.debug("this is debug")
console.trace("show trace")

参数个数太多,可以用对象代替

🐨参数顺序无关紧要

🐨方便传递可选参数

例如:

function getBox(type, size, price, color) {}

getBox('carry', undefined, 10, 'red')

改进后:

function getBox(options) {
    const {type, size, price, color} = options
}

getBox({
    type: 'carry',
    price: 10,
    color: 'red'
})

用对象字面量替换switch语句

老实说,我也喜欢switch,但我其实并不知道什么时候使用switch语句和对象字面量。我依靠直觉来判断该选哪一个。

例如:

let drink
switch(type) {
    case 'cappuccino':
        drink = 'Cappuccino';
        break;
    case 'flatWhite':
        drink = 'Flat White';
        break;
    case 'espresso':
        drink = 'Espresso';
        break;
    default:
        drink = 'Unknown drink';
}

可以改进为:

const menu = {
    'cappuccino': 'Cappuccino',
    'flatWhite': 'Flat White',
    'espresso': 'Espresso',
    'default': 'Unknown drink'
}

const drink = menu[type] || menu['default']

使用find查找数据

要通过其中一个属性从对象数组中查找对象的话,我们通常使用for循环

let inventory = [
  {name: 'Bananas', quantity: 5},
  {name: 'Apples', quantity: 10},
  {name: 'Grapes', quantity: 2}
];
// 在数组中找到 name 为 `Apples` 的对象
function getApples(arr, value) {
  return arr.find(obj => obj.name === 'Apples');  // <-- here
}

let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }

短路求值

如果我们必须根据另一个值来设置一个值不是falsy值,一般会使用if-else语句,就像这样:

function getUserRole(role) {
  let userRole;

  // If role is not falsy value
  // set `userRole` as passed `role` value
  if (role) {
    userRole = role;
  } else {

    // else set the `userRole` as USER
    userRole = 'USER';
  }

  return userRole;
}

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

简写方法:

但是使用短路求值(||),我们可以用一行代码执行此操作,如下所示:

function getUserRole(role) {
  return role || 'USER';  // <-- here
}

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

基本上,expression1 || expression2被评估为真表达式。因此,这就意味着如果第一部分为真,则不必费心求值表达式的其余部分。

计算数组的平均值

const average = (arr) => arr.reduce((a, b) => a + b) / arr.length
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值