> For the complete documentation index, see [llms.txt](https://shhn0509.gitbook.io/javascript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shhn0509.gitbook.io/javascript/js-upgrade/euid-junior/watcha.md).

# 왓챠 예제

20201114 오프라인 수업 정리

### **셔플 함수** <a href="#shuffle" id="shuffle"></a>

* 왓챠의 메인페이지는 페이지를 새로고침 할 때마다 배경 이미지가 바뀐다. 셔플을 사용해서 매번 페이지가 로드 될 때마다 랜덤으로 이미지가 선택되어 페이지 배경으로 로드된다.
* 해당 함수를 만들기 위해 사용되는 기능

  * [`slice()`](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)메서드를 사용해서 기존의 배열이 손상되지 않도록 복사하여 새로운 배열을 생성 한다
  * [`sort()`](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)메서드를 사용해서 배열의 아이템들을 정열한다.
  * [`Math.random()`](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/random)메서드를 사용해서 랜덤으로 아이템이 선택되게 한다.

  ```javascript
  // 배열의 아이템을 뒤섞어서 새로운 배열 반환
  var shuffle = function (array) {
    return array.slice().sort(function () {
      return Math.random() - 0.5;
    });
  };
  ```
* `Math.random() - 0.5` 구문에서 `- 0.5`가 있을 떄와 없을 때의 차이점&#x20;

![-0.5를 적용 했을 때](/files/-MS9JAmEd5hKKVytKj4M)

![-0.5를 적용하지 않았을 때](/files/-MS9JCbyy6HnMgPWG3K5)

### **동적으로 스타일 규칙 추가하는 함수** <a href="#util-function" id="util-function"></a>

* 기존의 CSS에 직접적으로 스타일을 추가 하는 방식이 아닌 함수를 사용해서 동적으로 스타일 규칙을 추가하는 함수를 만든다.&#x20;

```javascript
var insertStyleRules = (function (style) {
  "use strict";

  var sheet = document.head.appendChild(style).sheet;

  // 클로저 함수
  return function (selector, rules) {
    var cssRulesString = Object.keys(rules)
      .map(function (key) {
        var value = rules[key];
        return key + ":" + value;
      })
      .join(";");

    sheet.insertRule(
      selector + "{" + cssRulesString + "}",
      sheet.cssRules.length
    );
  };
})(document.createElement("style")); // <style></style>
```

### 공부 메모 <a href="#memo" id="memo"></a>

* 크롬 깃허브 파일 트리 사이드바 토글 단축키
  * `Ctrl` + `Shift` + `S`
* 사이드바 찾기 단축키
  * `Shift` + `S`
