10 个干净的代码示例(Javascript)。

2025-05-26

10 个干净的代码示例(Javascript)。

1. 使用三元运算符有条件地为同一事物赋值。

  
a > b ? foo = 'apple' : foo = 'ball'; 

✔️  
foo = a > b ? 'apple' : 'ball';
Enter fullscreen mode Exit fullscreen mode

2.有条件地为特定对象属性分配相同的值。

  
c > d ? a.foo = 'apple' : a.bar = 'apple';

✔️  
a = { [c > d ? 'foo' : 'bar']: 'apple' };
Enter fullscreen mode Exit fullscreen mode

3.导出多个变量

 
export const foo;
export const bar;
export const kip;

✔️ 
export const foo, bar, kip;
Enter fullscreen mode Exit fullscreen mode

4.从对象属性声明和分配变量。

  
const a = foo.x, b = foo.y;

✔️
const { ['x']: a, ['y']: b } = foo;
Enter fullscreen mode Exit fullscreen mode

5. 从数组索引声明和分配变量。

  
let a = foo[0], b = foo[1];

✔️
let [a, b] = foo;
Enter fullscreen mode Exit fullscreen mode

6.从 DOM 获取多个元素。

  
const a = document.getElementById('a'),
b = document.getElementById('b'),
c = document.getElementById('c');
d = document.getElementById('d');

✔️
const elements = {};
['a', 'b', 'c', 'd'].forEach(item => elements = { 
  ...elements, 
  [item]: document.getElementById(item) 
});
const { a, b, c, d } = elements;

/*
For this to work your elements ID's must be 
able to be valid Javascript variable names
and the names of the variables in which you store
your elements have to match with that elements' ID.
This is good for naming consistency & accesibility.
*/
Enter fullscreen mode Exit fullscreen mode

7. 使用逻辑运算符进行简单的条件判断。

  
if (foo) {
  doSomething();
}

✔️
foo && doSomething();
Enter fullscreen mode Exit fullscreen mode

8.有条件地传递参数。

  
if(!foo){
  foo = 'apple';
}
bar(foo, kip);

✔️
bar(foo || 'apple', kip);
Enter fullscreen mode Exit fullscreen mode

9. 处理大量的 0。

`

  
const SALARY = 150000000,
TAX = 15000000;

✔️
const SALARY = 15e7,
TAX = 15e6;
Enter fullscreen mode Exit fullscreen mode


``

10.将同一件事物赋给多个变量。

``

  
a = d;
b = d;
c = d;

✔️
a = b = c = d;
Enter fullscreen mode Exit fullscreen mode


``

Bonus⭐(一个调试技巧)

一遍又一遍地重复写代码调试起来console.log()可能很麻烦。你可以使用对象解构 赋值来简化它。

``

const { ['log']: c } = console;
c("something");
Enter fullscreen mode Exit fullscreen mode


``

现在,您不必写出来,console.log()
只需写下来即可,c()这样更容易编写,
调试速度更快。

感谢阅读!🎉。

查看我的 github

文章来源:https://dev.to/redbossrabbit/10-clean-code-examples-javascript-37kj
PREV
用户故事已经足够了!
NEXT
薪资谈判的基础知识