---
# System prepended metadata

title: 常用筆記

---

# 常用筆記
### 小數點去除補 0, 防止浮點異位
``` js=
const formatter = new Intl.NumberFormat('en-US', {
  style: 'decimal',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});

console.log(formatter.format(372.24-116.85));
```
### 一行程式new出二維陣列
```javascript=
apple = new Array(10).fill(null).map(()=>new Array(10).fill(null));
```
### 一行程式new 一維陣列 並且產生隨機數
```javascript=
Array(3).fill().map(() => Math.round(Math.random() * 10))
```
### 根據數量產生陣列預設值
```javascript=
[...Array(10)].map((it,index)=>index)
```

### 比較版本號
``` ts=
export const compareVersion = (currentVersion: string, newVersion: string) => {
  const v1 = currentVersion.split('.').map(Number);
  const v2 = newVersion.split('.').map(Number);

  for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
    const num1 = v1[i] || 0;
    const num2 = v2[i] || 0;

    if (num1 < num2) return true; // version2 is greater if any corresponding part is greater
    if (num1 > num2) return false; // version1 is greater if any corresponding part is greater
  }

  return false; // versions are equal
};

// Example usage:
const oldVersion = '1.0.1';
const newVersion = '1.2.3';

if (compareVersions(oldVersion, newVersion)) {
  console.log(newVersion + ' is an update over ' + oldVersion);
} else {
  console.log(newVersion + ' is not an update over ' + oldVersion);
}

```
### Array 轉 Object
![](https://hackmd.io/_uploads/HJYEomHWT.png)

Object.fromEntries 能把元素[key,value]
轉成對應的 object

### Object 轉 Array
![](https://hackmd.io/_uploads/rJJjomSZa.png)


### 正則過濾 只留下數字
``` JS=
let str = '001a0123vbas2!35#%';
str.replace(/[^\d]/g, "")
```

### JS引用檔案方式對比
#### module exports (CommonJS)
* require 
    Node.js 和 ES6 都支援的引入
* export / import 
    只有ES6 支援的導出引入
* module.exports / exports 
    CommonJS


### 去除浮點數 || 字串轉數字
``` javascript=
let test = "123"
let numberTest = test >> 0
```


### Date.now 轉成 yyyy-mm-dd
``` js=
new Date().toISOString().slice(0, 10)
```

### 檢查陣列元素是否有empty元素
``` js=
array.includes(undefined);
```

### 檢查陣列內元素是否重複
``` js=
function checkIfDuplicateExists(arr) {
    return new Set(arr).size !== arr.length
}
var arr = ["a", "a", "b", "c"];
var arr1 = ["a", "b", "c"];

console.log(checkIfDuplicateExists(arr)); // true
console.log(checkIfDuplicateExists(arr1)); // false
```
### object轉base64 base64轉object(能傳到網址query)
Base64 編碼後的字串可能包含一些字元，
在網址中使用時可能會產生問題。
例如在網址中使用 + 字元時，
會被解讀為空格。為了避免這個問題，
可以使用 URL-safe Base64 編碼，
即將 + 和 / 字元替換為 - 和 _ 字元。
這樣在網址中使用時就不會產生問題了。

>加密
``` js=
const obj = {
  name: '小明',
  age: 18,
  hobbies: ['reading', 'swimming', 'traveling']
};

const arr = Object.values(obj);
const jsonStr = JSON.stringify(arr);
const encoder = new TextEncoder();
const uint8Array = encoder.encode(jsonStr);
const base64Str = btoa(String.fromCharCode(...uint8Array)).replace(/\+/g, '-').replace(/\//g, '_');

console.log(base64Str); // "W3sibmFtZSI6IuW8oOWtlSIsImFnZSI6MTgsImhvYmJpZXMiOlsicmVhZGluZyIsInN3aW1tc2luZyIsInRyYXZlbGluZyJdfQ=="
```
>解密
``` js=
const base64Str = "W3sibmFtZSI6IuW8oOWtlSIsImFnZSI6MTgsImhvYmJpZXMiOlsicmVhZGluZyIsInN3aW1tc2luZyIsInRyYXZlbGluZyJdfQ==";
const base64Url = base64Str.replace(/-/g, '+').replace(/_/g, '/');
const uint8Array = Uint8Array.from(atob(base64Url), c => c.charCodeAt(0));
const decoder = new TextDecoder();
const jsonStr = decoder.decode(uint8Array);
const arr = JSON.parse(jsonStr);
const obj = Object.fromEntries(Object.keys(obj).map((key, index) => [key, arr[index]]));

console.log(obj); // {name: "小明", age: 18, hobbies: ["reading", "swimming", "traveling"]}
```


### object轉base64 base64轉object
``` js=
function utf8_to_base64(str) {
	return window.btoa(unescape(encodeURIComponent(str)));
}

function base64_to_utf8(str) {
	return decodeURIComponent(escape(window.atob(str)));
}

  utf8_to_base64(JSON.stringify(row)
  JSON.parse(base64_to_utf8(getUrlParameter("rowData"))
```

### js將一位數組分割成每n個一組
``` js=
function spArr(arr, num) { 
	let newArr = [] 
	for (let i = 0; i < arr.length;) { 沒有i++
		newArr.push(arr.slice(i, i += num));
	}
	return newArr
}
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(spArr(arr, 4))
```

### 每三位數字加逗號
``` js=
export function thousandSpr(x) {
  if (x === null || x === undefined) {
    return '';
  }

  const parts = x.toString().split('.');
  const replacement = ',';
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, replacement);

  return parts.join('.');
}
```

### 多層級物件展開一維陣列,並且也能轉回去
``` js=
// 函數將多層級物件轉換為一維數組
function flattenObject(obj, prefix = '') {
    const flatObject = {};

    for (const key in obj) {
        if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
            // 遞迴處理內部物件
            const nestedObject = flattenObject(obj[key], `${prefix}${key}.`);
            Object.assign(flatObject, nestedObject);
        } else {
            flatObject[`${prefix}${key}`] = obj[key];
        }
    }

    return flatObject;
}

// 函數將一維數組轉換回多層級物件結構
function unflattenObject(flatObject) {
    const nestedObject = {};

    for (const key in flatObject) {
        const keys = key.split('.');
        let currentObject = nestedObject;

        for (let i = 0; i < keys.length - 1; i++) {
            const nestedKey = keys[i];
            currentObject[nestedKey] = currentObject[nestedKey] || {};
            currentObject = currentObject[nestedKey];
        }

        currentObject[keys[keys.length - 1]] = flatObject[key];
    }

    return nestedObject;
}

// 原始多層級物件
const originalObject = {
    person: {
        name: 'Alice',
        address: {
            street: '123 Main St',
            city: 'Anytown',
        },
    },
    age: 30,
};

// 將多層級物件轉換為一維數組
const flatData = flattenObject(originalObject);

// 假設在一維數組上執行一些運算
for (const key in flatData) {
    if (typeof flatData[key] === 'number') {
        flatData[key] *= 2; // 假設將數字倍增
    }
}

// 將一維數組還原回多層級物件
const restoredObject = unflattenObject(flatData);

console.log('原始物件:');
console.log(originalObject);

console.log('\n一維數組:');
console.log(flatData);

console.log('\n還原後的物件:');
console.log(restoredObject);

```


### Date時間相關

#### date 轉成星期幾
```js=
new Date('2022-03-06').toLocaleString("cn", { weekday: "long" })
```

#### date to yyyy/mm/dd
處理時區
```js=
Date.prototype.toISOString = function () {
    let pad =(n)=>(n < 10)?'0' + n:n;
    let hours_offset = this.getTimezoneOffset() / 60;
    let offset_date = this.setHours(this.getHours() - hours_offset);
    let symbol = (hours_offset >= 0) ? "-" : "+";
    let time_zone = symbol+pad(Math.abs(hours_offset))+ ":00";
    
    return this.getUTCFullYear() +
        '-' + pad(this.getUTCMonth() + 1) +
        '-' + pad(this.getUTCDate()) +
        'T' + pad(this.getUTCHours()) +
        ':' + pad(this.getUTCMinutes()) +
        ':' + pad(this.getUTCSeconds()) +
        '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
        time_zone;
};
```
```js=
new Date().toISOString().slice(0, 10).replace(/-/g,'/')
```

``` js=
join("\\n\n")
```