>  기사  >  웹 프론트엔드  >  JavaScript 코딩을 위한 19가지 팁

JavaScript 코딩을 위한 19가지 팁

黄舟
黄舟원래의
2017-08-08 13:43:461073검색

이 글은 JavaScript 기반의 모든 개발자에게 적합합니다. 나는 모든 사람이 JavaScript의 기본 사항을 더 잘 이해할 수 있도록 돕기 위해 주로 JavaScript의 일부 축약된 코드에 대해 이 기사를 썼습니다. 이 코드가 JavaScript를 다양한 관점에서 이해하는 데 도움이 되기를 바랍니다.

삼차 연산자

if...else 문을 사용하면 코드를 절약하는 좋은 방법입니다. if...else语句,那么这是一个很好节省代码的方式。

Longhand:

const x = 20;
let answer;
if (x > 10) {
    answer = 'is greater';
} else {
    answer = 'is lesser';
}

Shorthand:

const answer = x > 10 ? 'is greater' : 'is lesser';

你还可以像下面这样嵌套if语句:

const big = x > 10 ? " greater 10" : x

Short-circuit Evaluation

分配一个变量值到另一个变量的时候,你可能想要确保变量不是nullundefined或空。你可以写一个有多个if的条件语句或者Short-circuit Evaluation。

Longhand:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}

Shorthand:

const variable2 = variable1  || 'new';

不要相信我,请先相信自己的测试(可以把下面的代码粘贴在es6console)

let variable1;
let variable2 = variable1  || '';
console.log(variable2 === ''); // prints true

variable1 = 'foo';
variable2 = variable1  || '';
console.log(variable2); // prints foo

声明变量

在函数中声明变量时,像下面这样同时声明多个变量可以节省你大量的时间和空间:

Longhand:

let x;
let y;
let x = 3;

Shorthand:

let x, y, z=3;

如果存在

这可能是微不足道的,但值得提及。做“如果检查”时,赋值操作符有时可以省略。

Longhand:

if (likeJavaScript === true)

Shorthand:

if (likeJavaScript)

注:这两种方法并不完全相同,简写检查只要likeJavaScripttrue都将通过。

这有另一个示例。如果a不是true,然后做什么。

Longhand:

let a;
if ( a !== true ) {
// do something...
}

Shorthand:

let a;
if ( !a ) {
// do something...
}

JavaScript的for循环

如果你只想要原生的JavaScript,而不想依赖于jQuery或Lodash这样的外部库,那这个小技巧是非常有用的。

Longhand:

for (let i = 0; i < allImgs.length; i++)

Shorthand:

for (let index in allImgs)

Array.forEach简写:

function logArrayElements(element, index, array) {
  console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9

Short-circuit Evaluation

如果参数是null或者是undefined,我们可以简单的使用一个Short-circuit逻辑运算,实现一行代码替代六行代码的写法。

Longhand:

let dbHost;
if (process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;
} else {
  dbHost = &#39;localhost&#39;;
}

Shorthand:

const dbHost = process.env.DB_HOST || &#39;localhost&#39;;

十进制指数

你可能看过这个。它本质上是一个写数字的奇特写法,就是一个数字后面有很多个0。例如1e7本质相当于100000001的后面有70)。它代表了十进制计数等于10000000

Longhand:

for (let i = 0; i < 10000; i++) {}

Shorthand:

for (let i = 0; i < 1e7; i++) {}
// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

对象属性

定义对象文字(Object literals)让JavaScript变得更有趣。ES6提供了一个更简单的办法来分配对象的属性。如果属性名和值一样,你可以使用下面简写的方式。

Longhand:

const obj = { x:x, y:y };

Shorthand:

const obj = { x, y };

箭头函数

经典函数很容易读和写,但它们确实会变得有点冗长,特别是嵌套函数中调用其他函数时还会让你感到困惑。

Longhand:

function sayHello(name) {
  console.log(&#39;Hello&#39;, name);
}

setTimeout(function() {
  console.log(&#39;Loaded&#39;)
}, 2000);

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

Shorthand:

sayHello = name => console.log(&#39;Hello&#39;, name);

setTimeout(() => console.log(&#39;Loaded&#39;), 2000);

list.forEach(item => console.log(item));

隐式返回

return在函数中经常使用到的一个关键词,将返回函数的最终结果。箭头函数用一个语句将隐式的返回结果(函数必须省略{},为了省略return关键词)。

如果返回一个多行语句(比如对象),有必要在函数体内使用()替代{}。这样可以确保代码是否作为一个单独的语句返回。

Longhand:

function calcCircumference(diameter) {
  return Math.PI * diameter
}

Shorthand:

calcCircumference = diameter => (
  Math.PI * diameter;
)

默认参数值

你可以使用if语句来定义函数参数的默认值。在ES6中,可以在函数声明中定义默认值。

Longhand:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}

Shorthand:

volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) //output: 24

Template Literals

是不是厌倦了使用+来连接多个变量变成一个字符串?难道就没有一个更容易的方法吗?如果你能使用ES6,那么你是幸运的。在ES6中,你要做的是使用撇号和${}

Longhand:

const welcome = &#39;You have logged in as &#39; + first + &#39; &#39; + last + &#39;.&#39;

const db = &#39;http://&#39; + host + &#39;:&#39; + port + &#39;/&#39; + database;

Shorthand:

const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;

다음과 같이 if 문을 중첩할 수도 있습니다.

const observable = require(&#39;mobx/observable&#39;);
const action = require(&#39;mobx/action&#39;);
const runInAction = require(&#39;mobx/runInAction&#39;);

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;

Short-circuit Evaluation

한 변수 값을 다른 변수에 할당 변수가 null, 정의되지 않음 또는 비어 있지 않은지 확인하는 것이 좋습니다. 여러 if를 사용하여 조건문이나 단락 평가를 작성할 수 있습니다. ㅋㅋㅋ 함수, 이와 같이 동시에 여러 변수를 선언하면 많은 시간과 공간을 절약할 수 있습니다.

Longhand:

import { observable, action, runInAction } from &#39;mobx&#39;;

const { store, form, loading, errors, entity } = this.props;
Shorthand:

const { store, form, loading, errors, entity:contact } = this.props;

존재하는 경우

사소할 수 있지만 언급할 가치가 있습니다. "if 검사"를 수행할 때 할당 연산자가 생략되는 경우가 있습니다. ㅋㅋㅋ 코드>가 통과됩니다.

여기 또 다른 예가 있습니다. atrue가 아닌 경우 어떻게 해야 할까요? ㅋㅋㅋ 🎜🎜🎜Longhand:🎜🎜
const lorem = &#39;Lorem ipsum dolor sit amet, consectetur\n\t&#39;
    + &#39;adipisicing elit, sed do eiusmod tempor incididunt\n\t&#39;
    + &#39;ut labore et dolore magna aliqua. Ut enim ad minim\n\t&#39;
    + &#39;veniam, quis nostrud exercitation ullamco laboris\n\t&#39;
    + &#39;nisi ut aliquip ex ea commodo consequat. Duis aute\n\t&#39;
    + &#39;irure dolor in reprehenderit in voluptate velit esse.\n\t&#39;
🎜🎜Shorthand:🎜🎜
const lorem = `Lorem ipsum dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse.`
🎜Array.forEachShorthand: 🎜
// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()
🎜Short-circuit Evaluation🎜🎜매개변수가 null인 경우 또는 정의되지 않음, 우리는 간단히 단락 논리 연산을 사용하여 여섯 줄의 코드를 한 줄의 코드로 바꿀 수 있습니다. 🎜🎜🎜긴 표기:🎜🎜
// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];
🎜🎜약칭:🎜🎜
const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];
🎜소수 지수🎜🎜이것을 본 적이 있을 것입니다. 숫자 뒤에 0이 많이 붙는 것은 본질적으로 숫자를 쓰는 이상한 방법입니다. 예를 들어, 1e7은 본질적으로 10000000과 동일합니다(1 뒤에 7 0가 옵니다). >) . 10000000과 같은 10진수 표기법을 나타냅니다. 🎜🎜🎜긴 표기:🎜🎜
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }
🎜🎜약칭:🎜🎜
function foo(bar) {
  if(bar === undefined) {
    throw new Error(&#39;Missing parameter!&#39;);
  }
  return bar;
}
🎜객체 속성🎜🎜객체 리터럴을 정의하여 JavaScript를 더욱 흥미롭게 만듭니다. ES6에서는 객체 속성을 할당하는 더 간단한 방법을 제공합니다. 속성 이름과 값이 동일한 경우 다음 약어를 사용할 수 있습니다. 🎜🎜🎜긴 표현:🎜🎜
mandatory = () => {
  throw new Error(&#39;Missing parameter!&#39;);
}

foo = (bar = mandatory()) => {
  return bar;
}
🎜🎜짧은 표현:🎜🎜
const pets = [
  { type: &#39;Dog&#39;, name: &#39;Max&#39;},
  { type: &#39;Cat&#39;, name: &#39;Karl&#39;},
  { type: &#39;Dog&#39;, name: &#39;Tommy&#39;},
]

function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === &#39;Dog&#39; && pets[i].name === name) {
      return pets[i];
    }
  }
}
🎜화살표 함수🎜🎜클래식 함수는 읽고 쓰기가 쉽지만, 특히 중첩된 함수가 다른 함수를 호출할 때 약간 장황해집니다. 🎜🎜🎜Longhand:🎜🎜
pet = pets.find(pet => pet.type ===&#39;Dog&#39; && pet.name === &#39;Tommy&#39;);
console.log(pet); // { type: &#39;Dog&#39;, name: &#39;Tommy&#39; }
🎜🎜Shorthand:🎜🎜
function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

console.log(validate({first:&#39;Bruce&#39;,last:&#39;Wayne&#39;})); // true
🎜Implicit return🎜🎜return함수에서 자주 사용되는 키워드는 함수의 최종 결과를 반환합니다. 화살표 함수는 암시적으로 단일 문으로 결과를 반환합니다(함수는 return 키워드를 생략하려면 {}를 생략해야 함). 🎜🎜여러 줄 문(예: 객체)을 반환하는 경우 함수 본문에서 {} 대신 ()를 사용해야 합니다. 이렇게 하면 코드가 별도의 문으로 반환됩니다. 🎜🎜🎜Longhand:🎜🎜
// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}

console.log(validate(schema, {first:&#39;Bruce&#39;})); // false
console.log(validate(schema, {first:&#39;Bruce&#39;,last:&#39;Wayne&#39;})); // true
🎜🎜Shorthand:🎜🎜
Math.floor(4.9) === 4  //true
🎜기본 매개변수 값🎜🎜 if 문을 사용하여 함수 매개변수의 기본값을 정의할 수 있습니다. ES6에서는 함수 선언에서 기본값을 정의할 수 있습니다. 🎜🎜🎜Longhand:🎜🎜
~~4.9 === 4  //true
🎜🎜Shorthand:🎜🎜rrreee🎜Template Literals🎜🎜+를 사용하여 여러 변수를 하나의 문자열로 연결하는 데 지치셨나요? 더 쉬운 방법은 없나요? ES6을 사용할 수 있다면 운이 좋은 것입니다. ES6에서 해야 할 일은 아포스트로피와 ${}를 사용하고 변수를 중괄호 안에 넣는 것입니다. ㅋㅋㅋ API 정보. 데이터 개체가 구성 요소에 도달하면 이를 확장해야 합니다. 🎜🎜🎜Longhand:🎜🎜rrreee🎜🎜Shorthand:🎜🎜rrreee🎜변수 이름을 직접 지정할 수도 있습니다. 🎜rrreee🎜Multiline string🎜🎜여러 줄 문자열을 작성하는 데 사용한 코드는 다음과 같습니다. 🎜

Longhand:

const lorem = &#39;Lorem ipsum dolor sit amet, consectetur\n\t&#39;
    + &#39;adipisicing elit, sed do eiusmod tempor incididunt\n\t&#39;
    + &#39;ut labore et dolore magna aliqua. Ut enim ad minim\n\t&#39;
    + &#39;veniam, quis nostrud exercitation ullamco laboris\n\t&#39;
    + &#39;nisi ut aliquip ex ea commodo consequat. Duis aute\n\t&#39;
    + &#39;irure dolor in reprehenderit in voluptate velit esse.\n\t&#39;

但还有一个更简单的方法。使用撇号。

Shorthand:

const lorem = `Lorem ipsum dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse.`

Spread Operator

Spread Operator是ES6中引入的,使JavaScript代码更高效和有趣。它可以用来代替某些数组的功能。Spread Operator只是一个系列的三个点(...)。

Longhand:

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

Shorthand:

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

不像concat()函数,使用Spread Operator你可以将一个数组插入到另一个数组的任何地方。

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];

另外还可以当作解构符:

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }

强制参数

默认情况下,JavaScript如果不给函数参数传一个值的话,将会是一个undefined。有些语言也将抛出一个警告或错误。在执行参数赋值时,你可以使用if语句,如果未定义将会抛出一个错误,或者你可以使用强制参数(Mandatory parameter)。

Longhand:

function foo(bar) {
  if(bar === undefined) {
    throw new Error(&#39;Missing parameter!&#39;);
  }
  return bar;
}

Shorthand:

mandatory = () => {
  throw new Error(&#39;Missing parameter!&#39;);
}

foo = (bar = mandatory()) => {
  return bar;
}

Array.find

如果你以前写过一个查找函数,你可能会使用一个for循环。在ES6中,你可以使用数组的一个新功能find()

Longhand:

const pets = [
  { type: &#39;Dog&#39;, name: &#39;Max&#39;},
  { type: &#39;Cat&#39;, name: &#39;Karl&#39;},
  { type: &#39;Dog&#39;, name: &#39;Tommy&#39;},
]

function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === &#39;Dog&#39; && pets[i].name === name) {
      return pets[i];
    }
  }
}

Shorthand:

pet = pets.find(pet => pet.type ===&#39;Dog&#39; && pet.name === &#39;Tommy&#39;);
console.log(pet); // { type: &#39;Dog&#39;, name: &#39;Tommy&#39; }

Object[key]

你知道Foo.bar也可以写成Foo[bar]吧。起初,似乎没有理由应该这样写。然而,这个符号可以让你编写可重用代码块。

下面是一段简化后的函数的例子:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

console.log(validate({first:&#39;Bruce&#39;,last:&#39;Wayne&#39;})); // true

这个函数可以正常工作。然而,需要考虑一个这样的场景:有很多种形式需要应用验证,而且不同领域有不同规则。在运行时很难创建一个通用的验证功能。

Shorthand:

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}

console.log(validate(schema, {first:&#39;Bruce&#39;})); // false
console.log(validate(schema, {first:&#39;Bruce&#39;,last:&#39;Wayne&#39;})); // true

现在我们有一个验证函数,可以各种形式的重用,而不需要为每个不同的功能定制一个验证函数。

Double Bitwise NOT

如果你是一位JavaScript新手的话,对于逐位运算符(Bitwise Operator)你应该永远不会在任何地方使用。此外,如果你不处理二进制01,那就更不会想使用。

然而,一个非常实用的用例,那就是双位操作符。你可以用它替代Math.floor()。Double Bitwise NOT运算符有很大的优势,它执行相同的操作要快得多。你可以在这里阅读更多关于位运算符相关的知识。

Longhand:

Math.floor(4.9) === 4  //true

Shorthand:

~~4.9 === 4  //true

위 내용은 JavaScript 코딩을 위한 19가지 팁의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.