关于javascript:初学者8个JavaScript技巧

44次阅读

共计 2549 个字符,预计需要花费 7 分钟才能阅读完成。

有很多办法能够优化咱们的 JavaScript 代码,本文总结了我在工作中常常应用的 8 个 JavaScript 技巧,心愿它也能帮忙你。

<!– more –>

缩小应用 if-else

在编写两个以上的 if … else 时,是否有更好的优化办法?
如下代码,咱们须要依据一个汉堡包的名字来计算它的价格。

const getPriceByName = (name) => {if (name === '🍔') {return 30;} else if (name === '🍨') {return 20;} else if (name === '🍿') {return 10;}
};
console.log(getPriceByName('🍔')); // 30

更好的写法 ✅

const getPriceByName = (name) => {
  const foodMap = {
    '🍔': 30,
    '🍨': 20,
    '🍿': 10,
    // 其余食物
    // ...
  };
  return foodMap[name];
};
console.log(getPriceByName('🍔')); // 30

应用 “filter” 和 “map”

当初,如果让你找到属于第 1 组的食物,你会如何找到它?比方上面这样数据:

const foods = [
  {
    name: '🍔',
    group: 1,
  },
  {
    name: '🍨',
    group: 1,
  },
  {
    name: '🍿',
    group: 2,
  },
  {
    name: '🍵',
    group: 1,
  },
];
// ❌
const names = [];
for (let i = 0, len = foods.length; i < len; i++) {if (foods[i].group === 1) {names.push(foods[i].name);
  }
}
// ✅
const names = foods.filter((food) => food.group === 1).map((food) => food.name);
console.log(names); // ['🍔', '🍨', '🍵']

应用解构法替换两个值

当初我有汉堡包,你有巧克力。咱们是好敌人,想替换食物。咱们通常怎么做呢?

// ❌
let myFood = '🍔';
let yourFood = '🍫';
let tempFoot = myFood;
myFood = yourFood;
yourFood = tempFoot;
console.log(myFood, yourFood); // 🍫 🍔

// ✅
let myFood = '🍔';
let yourFood = ('🍫'[(myFood, yourFood)] = [yourFood, myFood]);
console.log(myFood, yourFood); // 🍫 🍔

Object.entries

如果你想晓得仓库里食品的名称和价格,你应该怎么做?

const foodMap = {
  '🍔': 30,
  '🍨': 20,
  '🍿': 10,
  '🍫': 5,
};
// pay attention here
Object.prototype['🌭'] = 40;
// ❌ for in 遍历
for (const key in foodMap) {console.log(key, foodMap[key]);
}

// ✅
Object.entries(foodMap).forEach(([key, value]) => {console.log(key, value);
});

应用 Object. entries 至多有两个益处:

只打印对象上的属性,原型上的属性被疏忽。
间接获取对象的值,而不是用 obj[key] 来读取。

扁平化数组

这里有一组这样的数据

const foods = [[ '🍔', [ '🍫'] ], ['🍨', [ '🍿', [ '🍵'] ] ] ]
// ❌
const flattenFoods = (foods) => {return foods.reduce((res, food) => {return res.concat(Array.isArray(food) ? flattenFoods(food) : food);
  }, []);
};
console.log(flattenFoods(foods)); // ['🍔', '🍫', '🍨', '🍿', '🍵']

// ✅ 是不是很简略
foods.flat(Infinity); // ['🍔', '🍫', '🍨', '🍿', '🍵']

~~ 技巧

哇,明天是万圣节,为了庆贺这个节日,所有的食物都打折,小数点都被抹去。怎么实现

const foods = [
  {
    name: '🍔',
    price: 30.89,
  },
  {
    name: '🍨',
    price: 20.71,
  },
  {
    name: '🍿',
    price: 10.31,
  },
];
const discountedFoods = foods.map((it) => {
  return {
    name: it.name,
    price: ~~it.price,
  };
});
console.log(discountedFoods);

应用 reduce 来计算总和

计算总和:

const foods = [
  {
    name: '🍔',
    price: 30,
    amount: 10,
  },
  {
    name: '🍨',
    price: 20,
    amount: 3,
  },
  {
    name: '🍿',
    price: 10,
    amount: 5,
  },
  {
    name: '🍵',
    price: 5,
    amount: 9,
  },
];

// ❌
let sum = 0;
foods.forEach((food) => {sum += food.price * food.amount;});
console.log(sum); // 455

// ✅
let sum = foods.reduce((res, food) => res += food.price * food.amount, 0)
console.log(sum) // 455

console.table

咱们常常应用 console.log 来打印一些信息,但有时并不那么直观。

const foods = [
  {
    name: '🍔',
    price: 30.89,
    group: 1,
  },
  {
    name: '🍨',
    price: 20.71,
    group: 1,
  },
  {
    name: '🍿',
    price: 10.31,
    group: 2,
  },
  {
    name: '🍵',
    price: 5.98,
    group: 2,
  },
]
console.log(foods)

原文:https://javascript.plainenglish.io/8-javascript-tricks-to-mak…

公号同步更新,欢送关注 👻

正文完
 0