const fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
const csv = fruits.valueOf(); // "apple,peaches,oranges,mangoes"
// 自定義分隔符
const custom = fruits.join('|'); // "apple|peaches|oranges|mangoes"
const str = "apple, peaches, oranges, mangoes";
const arr = str.split(","); // ["apple", " peaches", " oranges", " mangoes"]
// 建議配合 map 去除空格
const clean = str.split(",").map(s => s.trim());
function removeByIndex(arr, index) {
arr.splice(index, 1);
}
const test = ['Apple', 'Ball', 'Cat', 'Dog'];
removeByIndex(test, 2); // 移除 'Cat',結果: ['Apple', 'Ball', 'Dog']
// 普通函數
function removeByValue(arr, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === val) {
arr.splice(i, 1);
break;
}
}
}
// 原型擴展(慎用,污染原型鏈)
Array.prototype.removeByValue = function(val) {
const idx = this.indexOf(val);
if (idx !== -1) this.splice(idx, 1);
};
const strFun = "someFunction";
const strParam = "this is the parameter";
const fn = window[strFun];
if (typeof fn === 'function') fn(strParam);
// ES6 更安全
const fn = (window[strFun] || Function.prototype).bind(window);
fn(strParam);
// 1 到 N
const random = Math.floor(Math.random() * N) + 1;
// 示例
const r10 = Math.floor(Math.random() * 10) + 1; // 1-10
const r100 = Math.floor(Math.random() * 100) + 1; // 1-100
window.addEventListener('beforeunload', (e) => {
e.preventDefault();
e.returnValue = '您有未保存的內容,確定離開?';
return e.returnValue;
});
window.onbeforeunload = () => '您的操作將不會被保存。';
function isFormDirty(form) {
return Array.from(form.elements).some(el => {
if (el.type === 'checkbox' || el.type === 'radio')
return el.checked !== el.defaultChecked;
return el.value !== el.defaultValue;
});
}
JSON.parse(JSON.stringify(obj))(不含函數/RegExp/Date)const debounce = (fn, ms) => { let t; return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); }; }const throttle = (fn, ms) => { let last = 0; return (...args) => { const now = Date.now(); if (now - last >= ms) { last = now; fn(...args); } }; }() => Math.random().toString(36).substr(2, 9)arr.flat(Infinity) (ES2019)const { oldName: newName, ...rest } = obj;這些技巧適用於快速原型開發、算法題、工具函數庫構建。生產環境複雜邏輯請使用成熟庫,注意代碼可讀性與維護性。