减少 JavaScript 编写的 9 个技巧。

2025-06-07

减少 JavaScript 编写的 9 个技巧。

嗨,Dev👋,感谢你打开我的博客。希望你一切顺利,并准备好学习一些减少 JavaScript 代码编写的技巧😎。

那么,我们开始吧!

1.声明变量

//Longhand
let x;
let y;
let z = "post";

//Shorthand
let x, y, z = "post";
Enter fullscreen mode Exit fullscreen mode

2.赋值运算符

//Longhand
x = x + y;
x = x - y;

//Shorthand
x += y;
x -= y;
Enter fullscreen mode Exit fullscreen mode

3.三元运算符

let answer, num = 15;

//Longhand
if (num > 10) {
  answer = "greater than 10";
} 
else {
  answer = "less than 10";
}

//Shorthand
const answer = num > 10 ? "greater than 10" : "less than 10";
Enter fullscreen mode Exit fullscreen mode

4. 短 for 循环

const languages = ["html", "css", "js"];

//Longhand
for (let i = 0; i < languages.length; i++) {
  const language = languages[i];
  console.log(language);
}

//Shorthand
for (let language of languages) console.log(language);
Enter fullscreen mode Exit fullscreen mode

5. 模板字符串

const name = "Dev";
const timeOfDay = "afternoon";

//Longhand
const greeting = "Hello " + name + ", I wish you a good " + timeOfDay + "!";

//Shorthand
const greeting = `Hello ${name}, I wish you a good ${timeOfDay}!`;
Enter fullscreen mode Exit fullscreen mode

6.箭头函数

//Longhand
function sayHello(name) {
  console.log("Hello", name);
}

list.forEach(function (item) {
  console.log(item);
});

//Shorthand
sayHello = name => console.log("Hello", name);

list.forEach(item => console.log(item));
Enter fullscreen mode Exit fullscreen mode

7. 对象数组表示法

//Longhand
let arr = new Array();
arr[0] = "html";
arr[1] = "css";
arr[2] = "js";

//Shorthand
let arr = ["html", "css", "js"];
Enter fullscreen mode Exit fullscreen mode

8.对象解构

const post = {
  data: {
    id: 1,
    title: "9 trick to write less Javascript",
    text: "Hello World!",
    author: "Shoaib Sayyed",
  },
};

//Longhand
const id = post.data.id;
const title = post.data.title;
const text = post.data.text;
const author = post.data.author;

//Shorthand
const { id, title, text, author } = post.data;
Enter fullscreen mode Exit fullscreen mode

9. 具有相同键和值的对象

//Longhand
const userDetails = {
  name: name, // 'name' key = 'name' variable
  email: email,
  age: age,
  location: location,
};

//Shorthand
const userDetails = { name, email, age, location };
Enter fullscreen mode Exit fullscreen mode

就是这样😎。

感谢阅读!我叫 Shoaib Sayyed,我喜欢帮助大家学习新技能😊。如果您想收到新文章和资源的通知,可以关注我。

文章来源:https://dev.to/thedreamydev/9-tricks-to-write-less-javascript-507i
PREV
基本 Docker 命令
NEXT
女演员学习编程