---
# System prepended metadata

title: 'JavaScript-[未整理的內容]'
tags: [Javascript]

---

JavaScript-[未整理的內容]
===
###### tags: `Javascript`

怎麼打前端基礎?

[前端面試手冊en](https://github.com/yangshun/front-end-interview-handbook/blob/master/contents/en/javascript-questions.md)

[前端面試手冊zh](https://github.com/yangshun/front-end-interview-handbook/tree/master/contents/zh)




---

[問答摘錄]
問:
moment toISOString 時區+8 要怎麼判斷 是要看系統架在哪邊嗎 還是前端可以判斷 USER LOCAL 
答:
認真讀完這篇文章，你會更熟悉時間操作
[淺談 JavaScript 中的時間與時區處理](https://blog.techbridge.cc/2020/12/26/javascript-date-time-and-timezone/
)

moment 在用的時候要 set timezoe, 轉出來的時區才會是你要的時區



---


[Blob / base64](https://jiepeng.me/2018/04/17/use-blob-and-file-web-api-create-upload-image-preview-immediately)




Hello:base64 會比 blob 大 8/6 倍

[Why do we use Base64?](https://stackoverflow.com/questions/3538021/why-do-we-use-base64)

Hello: 
[social media 搭配  nosql處理圖形](https://www.8bitmen.com/instagram-architecture-how-does-it-store-search-billions-of-images/)

[Youtube如何存影片](https://www.8bitmen.com/youtube-database-how-does-it-store-so-many-videos-without-running-out-of-storage-space/)

[Instagram如何存圖片](https://www.youtube.com/watch?v=QyY5gqCnCzM)


忘記這是在問什麼了
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

[滾輪特效Scroll Magic](https://scrollmagic.io)

---

TypeScript教學推薦
[官方](https://www.typescriptlang.org/)
[H大推薦但是要錢](https://frontendmasters.com/courses/typescript-v2)


---

增進coding能力
[Codewar](https://www.codewars.com/)


---

# 淺拷貝(shallow copy) & 深拷貝(deep copy)
Hello:    如果純粹JSON的話，直接用 JSON.parse 就可以了
Hello:    速度似乎比生成一個物件還快 **(註1)**
Hello:    deepClone **(註2)** 不應該是高頻率的操作
竹子:      deepClone 通常是為了複製 Functon 吧
recoil:   Object[ ]只能建議用lodash深複製了嗎?
竹子:      你可以自己寫遞迴XDXD
recoil:   那最好方案就是[].map(item=>JSON.parse(JSON.stringify(item)))了

註1:![](https://i.imgur.com/zSDH5GH.png)
註2: [lodash](https://lodash.com/)是一個第三方套件，裡面有許多常用涵式可提供工程師操作數據

# 動畫效能
## requestAnimationFrame

[效能相關影片](https://www.youtube.com/watch?v=cCOL7MC4Pl0&t=3s)
主要是真的要調整效能的話，要先了解**底層**的機制。
canvas 跑會比 DOM 好很多，因為 DOM Element 很大，而且某些 API 會強制 redraw 跟 reframe，建議 JS 能不用開 thread 就不用

* 在無法避免他跑到重新render的時候該怎麼減少效能的消耗？
    * 計算完結果再一次刷新上去，有點像批次處理的概念
    * 跟傳統的遊戲寫法或 GL programing 也有相同概念
* 前端的thread為什麼最好避免去使用?
    * 因為原本就有，可以看[效能相關影片](https://www.youtube.com/watch?v=cCOL7MC4Pl0&t=3s)，了解一下**event loop**。
    * 在 browser 主要會發生 畫面卡頓的原因
        1. main thread block
        2. force redraw
        3. draw process too long
    * 當開 thread 不能解決問題 就不應該開，然後 v8 原本就有至少 6 條 thread 在跑，JS 是跑在 main thread 上面，比較繁重的任務會被委派到其他的 thread，當解決的時候會被 queue 進 task queue，等到下次 event loop 去拿結果，大部分的計算不會跑到需要另外開一條來算，包含物理演算。畫面的計算會由 render process 下去委派 GPU 算。這邊跟 JS 沒關係了。所以 JS 任務很簡單就是算出結果丟給別人。
* 動畫相關 或 遊戲相關 建議用 requestAnimationFrame 取代 timeout
    * 原因在效能相關影片17分左右，![原理](https://i.imgur.com/FFUE4EC.jpg)
    * rAF 固定會在 render 之前，timeout 不一定，timeout 並不是絕對會在那個時間執行
    * setTimeout ![setTimeout](https://i.imgur.com/skDHqaW.jpg)
    * rAF ![](https://i.imgur.com/AJHqnjq.jpg)
* 參考了一些資料 web worker 是由瀏覽器另外開立的一個 thread ，其運算的速度結果不影響原來的thread，既然如此在原本的 Event Loop 中除了對其的訪問之外，對原來的程式產生的影響為何?
    * 其實不是 JS 才有的問題
    1. 首先 thread 本身相較於其他任務就相對耗資源，尤其是**建立**跟**消滅**的時候，會因為其消滅觸發 GC，main GC 一定會 block main thread，所以通常 web worker 通常開了就是一直開下去
    2. 再來就是 JS worker 之間溝通一定是透過 message channel，不像其他語言直接是記憶體共享，所以還是要等 event loop，除非要算超重量級任務才需要考慮另開一條來跑，
    3. 再來跑在 Browser 跟跑在OS的最大差異是記憶體的分配，Browser 的記憶體分配量是看 browser 本身，跟 native app 的配額有差，所以降低負擔是寫 web app 的基本功，能夠借力使力才是良策。

---
將文字複製至剪貼簿
[How TO - Copy Text to Clipboard](https://www.w3schools.com/howto/howto_js_copy_clipboard.asp)
[Interact with the clipboard](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard)

---
```javascript=
document.getElementById('test').innerHTML = "Hello";
// id
document.write(5+6);
console.log("韭菜切割");
window.alert("切割韭菜");

var a = 5;
let b = 4;
//可被重新定義，無法設定前使用，只有在代碼塊區域（block scope）內有效
const c = 3;
//無法重新定義，無法設定前使用，只有在代碼塊區域（block scope）內有效

let length = 16;                               // Number
let lastName = "Johnson";                      // String
let x = {firstName:"John", lastName:"Doe"};    // Object

let x = 16 + 4 + "Volvo";
// 20Volvo
let x = "Volvo" + 16 + 4;
// Volvo164

const person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

person.lastName;
person["lastName"];
name = person.fullName();
name = person.fullName;

//避免將字串，數字，布林值設為物件。會使程式更複雜且降低執行速率

// <button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>

onchange  網頁標籤的值被改變的時候
onclick	 使用者點擊此標籤的時候
onmouseover	使用者將滑鼠覆蓋在上面的時候
onmouseout	使用者將滑鼠移開此標籤的時候
onkeydown	使用者按下某個按鈕的時候
onload	網頁載入結束的時候


let text = "We are the so-called \"Vikings\" from the north.";
// \\ \' \"
\b	Backspace
\f	Form Feed
\n	New Line
\r	Carriage Return
\t	Horizontal Tabulator
\v	Vertical Tabulator


let str = "Apple, Banana, Kiwi";
str.slice(7, 13) 
str.substring(7, 13)
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
let newText = text.replace(/MICROSOFT/i, "W3Schools");
let newText = text.replace(/Microsoft/g, "W3Schools");
//slice和substring相似,slice允許設定負數

let text1 = "Hello World!";     
let text2 = text1.toUpperCase();
let text2 = text1.toLowerCase();

let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);

let text = "       Hello World!        ";
text.trim()    // Returns "Hello World!"


let text = "5";
text.padStart(4,0)    // Returns 0005
text.padEnd(4,0)     // Returns 5000

let text = "HELLO WORLD";
text.charAt(0)           // Returns H
text.charCodeAt(0)       // Returns 72

text.split("") 

let text = "HELLO WORLD";
text[0] = "A"             // Gives no error, but does not work
text[0]                   // returns H


let str = "Please locate where 'locate' occurs!";
str.indexOf("locate")    // Returns 7
str.lastIndexOf("locate")    // Returns 21
str.lastIndexOf("John")    // Returns -1
str.indexOf("locate", 15)    // Returns 21
str.search("locate")     // Returns 7

let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g)    // Returns an array [ain,ain,ain]
text.match(/ain/gi)   // Returns an array [ain,AIN,ain,ain]

let text = "Hello world, welcome to the universe.";
text.includes("world")    // Returns true
text.includes("world", 12)    // Returns false
text.startsWith("Hello")   // Returns true
text.startsWith("world", 5)
text.endsWith("Doe")
text.endsWith("world", 11)

let text = `He's often called "Johnny"`;

let firstName = "John";
let lastName = "Doe";

let text = `Welcome ${firstName}, ${lastName}!`;

let price = 10;
let VAT = 0.25;

let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;


//此作法IE不支援
let header = "Templates Literals";
let tags = ["template literals", "javascript", "es6"];

let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
  html += `<li>${x}</li>`;
}

html += `</ul>`;



let myNumber = 32;
myNumber.toString(10);  // returns 32


let x = 9.656;
x.toExponential(2);     // returns 9.66e+0
x.toExponential(4);     // returns 9.6560e+0
x.toExponential(6);     // returns 9.656000e+0
//參數是可加可不加的

let x = 9.656;
x.toFixed(0);           // returns 10
x.toFixed(2);           // returns 9.66
x.toFixed(4);           // returns 9.6560
x.toFixed(6);           // returns 9.656000

let x = 9.656;
x.toPrecision();        // returns 9.656
x.toPrecision(2);       // returns 9.7
x.toPrecision(4);       // returns 9.656
x.toPrecision(6);       // returns 9.65600

Number()
parseInt()
parseFloat()
//NaN 代表不是數字 undefined

cars.length   // Returns the number of elements
cars.sort()   // Sorts the array


const fruits = ["Banana", "Orange", "Apple"];

fruits instanceof Array;

如果自行定義陣列index，型別會自動轉成物件

const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.pop();  // x = "Mango"

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");   // Adds "Kiwi" to fruits

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();   // Removes "Banana" from fruits

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");    // Adds "Lemon" to fruits

const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];           // Changes the first element in fruits to undefined

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");


const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];

// Concatenate (join) myGirls and myBoys
const myChildren = myGirls.concat(myBoys);  


const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);


const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();        // First sort the elements of fruits
fruits.reverse();     // Then reverse the order of the elements

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});



//The Fisher Yates Method
const points = [40, 100, 1, 5, 25, 10];

for (let i = points.length -1; i > 0; i--) {
  let j = Math.floor(Math.random() * i)
  let k = points[i]
  points[i] = points[j]
  points[j] = k
}



const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);

function myFunction(value, index, array) {
  txt += value + "<br>";
}


const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);

function myFunction(value, index, array) {
  return value * 2;
}


const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

function myFunction(total, value, index, array) {
  return total + value;
}

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

function myFunction(total, value) {
  return total + value;
}



const numbers = [45, 4, 9, 16, 25];
let sum = numbers1.reduceRight(myFunction);

function myFunction(total, value, index, array) {
  return total + value;
}



const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}



const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}

const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.includes("Mango"); // is true




const numbers = [4, 9, 16, 25, 29];
let first = numbers.findIndex(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}

Array.from("ABCDEFG")   // Returns [A,B,C,D,E,F,G]



const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();

for (let of keys) {
  text += x + "<br>";
}


//可以恆陣列，但還是能更動裡面的值
//恆陣列不可重新定一個內容相同的陣列

Math.round(x)
Math.ceil(x)
Math.floor(x)
Math.trunc(x)
Math.sign()
Math.pow()
Math.sqrt()
Math.abs()
Math.min()
Math.max()
Math.random()
Math.log(x)
Math.log2(8)


// Returns a random integer from 0 to 99:
Math.floor(Math.random() * 100);


const numbers = [45, 4, 9, 16, 25];

let txt = "";
for (let x in numbers) {
  txt += numbers[x];
}


const cars = ["BMW", "Volvo", "Mini"];

let text = "";
for (let x of cars) {
  text += x;
}


typeof "John"                 // Returns "string"
typeof 3.14                   // Returns "number"
typeof NaN                    // Returns "number"
typeof false                  // Returns "boolean"
typeof [1,2,3,4]              // Returns "object"
typeof {name:'John', age:34}  // Returns "object"
typeof new Date()             // Returns "object"
typeof function () {}         // Returns "function"
typeof myCar                  // Returns "undefined" *
typeof null                   // Returns "object"

const pattern = /e/;
pattern.test("The best things in life are free!");

try catch finally

JavaScript Scope 作用域

Block scope
Function scope
Global scope

Hoisting  提升

https://developer.mozilla.org/zh-TW/docs/Glossary/Hoisting

Strict mode 嚴格模式

Strict mode makes it easier to write "secure" JavaScript.

Strict mode changes previously accepted "bad syntax" into real errors.

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Strict_mode

this

arrow function 箭頭函式
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Functions/Arrow_functions

class

json

js debugging的方法

js best practice

js mistakes

js會有瀏覽器版本導致語法錯誤的問題

```