现代 JavaScript 的简单概念

2025-06-07

现代 JavaScript 的简单概念

在开始之前,请注意,这篇文章是我试图向自己解释这些概念,所以请确保我完全理解它们,并在需要时做好笔记。这些概念还有很多内容,但我的笔记将总结为一些非常基本的解释。

这些概念是:

  • 箭头函数,
  • 模板文字,
  • Var、Let 和 Const,
  • 三元(条件)运算符,
  • 简写对象赋值和
  • 扩展运算符。

箭头函数
简单来说,箭头函数就是用更短的形式书写的函数。它之所以被称为箭头函数,是因为它用箭头符号=>代替了“函数”这个词。

//regular function
function hello() {
  console.log('Hello');
}

//arrow function
const hello = () => {console.log('Hello')}
Enter fullscreen mode Exit fullscreen mode

模板字符串
我已经用了一段时间了,但一直不知道它叫什么。这是一种创建字符串的新方法。说实话,我不太清楚该如何解释它,所以我会演示一下:

const name = 'Ana';
const age = 32;
//regular string
console.log(name + " is " + age + " years "+ "old");

//template literal
console.log(`${name} is ${age} years old`);
Enter fullscreen mode Exit fullscreen mode

结果是一样的,但是写成模板文字更容易,我不必担心空格,而且代码看起来很整洁。

Var、Let 和 Const
总是使用const,除非你确定要重新赋值,否则使用let。基本上,var 已经死了 xx

三元运算符(或条件运算符)
非常酷,就像这里的大多数其他概念一样。它是唯一使用三个操作数的运算符,并且经常用来替代 if/them。
具体方法如下

//Using if
var todayIsFriday = false;
if(todayIsFriday){
  console.log('It is Fri-yay')
} else{
  console.log('Not quite there yet')
}

// using Ternary Operator
var todayIsMonday = true;
console.log(todayIsMonday ? 'Yey, another week' : 'Yey, it is not Monday')
Enter fullscreen mode Exit fullscreen mode

简写对象赋值
如果要定义一个对象,其键名与作为属性传递的变量名相同,则可以使用简写并简单地传递键名:

//regular
const abc = {
  a:a,
  b:b,
  c:c,
};

//shorthand
const efg = { e, f, g};
Enter fullscreen mode Exit fullscreen mode

展开运算符
最后但同样重要的是展开运算符……这个运算符解释起来有点棘手。基本上,它接受一个数组或对象并对其进行展开。展开运算符的语法是……

const obj1 = {a: 'a', b: 'b'};
const obj2 = {c: 'c', ...obj1};
console.log(obj2);

//The console will log: Object {  a: "a",  b: "b",  c: "c"}

Enter fullscreen mode Exit fullscreen mode

今天就讲到这里。
也许我的小笔记能帮助像我一样熟悉 JavaScript 的人。
如果你想自己尝试练习的话,我的 Codepen 里有所有这些代码
https://codepen.io/collection/DLMWOM/

大家星期一快乐!

文章来源:https://dev.to/pachicodes/simple-concepts-of-modern-javascript-50ig
PREV
面试时该问什么?
NEXT
自学开发人员的学习资源