3. Arrays (JS style guide)

코비코 koreanvisionarycoder ㅣ 2022. 11. 22. 11:07

no-array-constructor " 배열 생성 : 리터럴 문법 []


  • no-array-constructor 새로운 배열을 구성하기 위해 Array 리터럴 표기법을 선호하지 않는이유
    • single-argument pitfall : 단일 인수 함정.
    • Array global (array 전역)이 재정의 될 수 있다.
  • 배열 생성자를 사용하는 예외
    • Array 생성자를 사용하여 생성자에게 단일 숫자 인수를 제공하여 지정된 크기의 배열을 의도적으로 만드는 경우.
// eslint no-array-constructor: "error" 
//never use

Array(0, 1, 2)

new Array(0, 1, 2)
//eslint no-array-constructor: "error"
// good code
Array(500)

new Array(someOtherArray.length)

[0, 1, 2]

배열의 items 생성 : push


const someStack = [];

// bad
someStack[someStack.length] = 'christmas';

// good
someStack.push('christmas');

배열 복사 : ... spread operator


// bad
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i += 1) {
  itemsCopy[i] = items[i];
}

// good
const itemsCopy = [...items];

/*
const items = [1, 2, 3];

// good
const itemsCopy = [...items];
console.log(itemsCopy);
실행 결과
[ 1, 2, 3 ]
*/

terable 객체 -> 배열 : spreads ... > Array.from.


Array-like 오브젝트를 배열로 변환하려면 from을 사용합니다.

const foo = document.querySelectorAll('.foo');

// good
const nodes = Array.from(foo);

// best
const nodes = [...foo];

/* 실행 결과
[ HTMLButtonElement {},
  HTMLButtonElement {},
  HTMLButtonElement {},
  HTMLButtonElement {},
  HTMLButtonElement {} ]
단순히 {a:1,b:2,c:3}을 Array.from할 경우 빈 배열로 나옴. Array-like Object를 찾아보기
*/

iterable 객체 document.querySelectorAll('.foo') 의 __proto__ 는 NodeList

array-like 객체 -> 배열 : Array.from


let arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };
/*
Object
0: "foo"
1: "bar"
2: "baz"
length: 3
__proto__: Object
*/
// bad
const arr = Array.prototype.slice.call(arrLike);

// good
const arr = Array.from(arrLike); // ["foo", "bar", "baz"]
let arrLike = { '0': 'foo', 1: 'bar', 2: 'baz', length: 3 };
Array.from(arrLike); // ["foo", "bar", "baz"]

arrLike = { '212': 'foo', 1: 'bar', 2: 'baz', length: 3 };
Array.from(arrLike); // [undefined, "bar", "baz"]

유사 배열의 조건

  1. length 프로퍼티가 존재.
  2. index 번호가 0번부터 시작해서 1씩증가.

iterable map : Array.from > spread ...


Array.from 은 중간에 배열을 생성하는 것을 방지한다.

const bar = (v) => v + 1;
const foo = [1, 2, 3];

// bad
const baz = [...foo].map(bar);  // [2, 3, 4]

// good
const baz = Array.from(foo, bar)  // [2, 3, 4]

array-callback-return : 배열 메서드의 callback 에서 return 문을 사용해야 한다


  • return 을 빼뜨린 것은 아마도 실수 일 것이다. 
  • return을 사용하지 않거나 반환된 결과가 필요하지 않는다면 forEach 를 사용하는 것이 좋다.
// good
[1, 2, 3].map((x) => {
  const y = x + 1;
  return x * y;
});

// good
[1, 2, 3].map((x) => x + 1);

// bad - callback 에서 return 문을 쓰지 않으면, 첫 이터레이션 이후 `acc` 의 값은 undefined 가 된다.
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
  const flatten = acc.concat(item);
});

// good
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
  const flatten = acc.concat(item);
  return flatten;
});

// bad
inbox.filter((msg) => {
  const { subject, author } = msg;
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee';
  } else {
    return false;
  }
});

// good
inbox.filter((msg) => {
  const { subject, author } = msg;
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee';
  }

  return false;
});
  • Array.from
  • Array.prototype.every
  • Array.prototype.filter
  • Array.prototype.find
  • Array.prototype.findIndex
  • Array.prototype.flatMap
  • Array.prototype.forEach(선택 사항)
  • Array.prototype.map
  • Array.prototype.reduce
  • Array.prototype.reduceRight
  • Array.prototype.some
  • Array.prototype.sort

여러 줄이있는 배열의 줄바꿈 : 괄호를 열때와 닫기전 사용


// bad
const arr = [
  [0, 1], [2, 3], [4, 5],
];

const objectInArray = [{
  id: 1,
}, {
  id: 2,
}];

const numberInArray = [
  1, 2,
];

// good
const arr = [[0, 1], [2, 3], [4, 5]];

const objectInArray = [
  {
    id: 1,
  },
  {
    id: 2,
  },
];

const numberInArray = [
  1,
  2,
];

'JS > 자바스크립트 Style Guide' 카테고리의 다른 글

5. Strings (JS style guide)  (0) 2022.12.07
4. Destructuring (JS style guide)  (0) 2022.12.02
2. Objects (JS style guide)  (0) 2022.11.18
1. References (JS style guide)  (0) 2022.11.18
0. Types (JS style guide)  (0) 2022.11.18