重写 Array.filter()
javascript复制代码Array.prototype.myFilter = function(callback, thisArg) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (callback.call(thisArg, this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};
// 测试
const arr = [1, 2, 3, 4, 5];
const filteredArr = arr.myFilter(num => num > 2);
console.log(filteredArr); // [3, 4, 5]
算法1:合并两个已排序的数组
javascript复制代码function mergeSortedArrays(arr1, arr2) {
let i = 0, j = 0;
const result = [];
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
result.push(arr1[i]);
i++;
} else {
result.push(arr2[j]);
j++;
}
}
// 处理剩余元素
return result.concat(arr1.slice(i)).concat(arr2.slice(j));
}
// 测试
const arr1 = [1, 3, 5, 7];
const arr2 = [2, 4, 6, 8];
console.log(mergeSortedArrays(arr1, arr2)); // [1, 2, 3, 4, 5, 6, 7, 8]
算法2:数值序列化(每隔三位一个逗号)
javascript复制代码function numberWithCommas(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// 测试
const num = 1234567890;
console.log(numberWithCommas(num)); // 1,234,567,890
算法3:格式化 query 字符串
javascript复制代码function parseQueryString(queryString) {
const queryObj = {};
const pairs = queryString.replace(/^\?/, '').split('&');
for (const pair of pairs) {
const [key, value] = pair.split('=');
if (queryObj[key]) {
if (Array.isArray(queryObj[key])) {
queryObj[key].push(decodeURIComponent(value));
} else {
queryObj[key] = [queryObj[key], decodeURIComponent(value)];
}
} else {
queryObj[key] = decodeURIComponent(value);
}
}
return queryObj;
}
// 测试
const queryString = '?a=1&a=2&b=3';
console.log(parseQueryString(queryString)); // { a: ['1', '2'], b: '3' }