面试题总结
程序员文章站
2024-03-24 23:01:28
...
1 JSON key 驼峰转换
实现一个转换函数covert,将JSON对象的下划线keys({a_jh_dhs: 99})转化为驼峰形式 {aIhDhs: 99}
function getCase(obj) {
const reg = /_(.)/g
function keyToCase(str) {
if(typeof str !== 'string') return ''
return str.replace(reg, (match, $) => {
return $.toUpperCase()
})
}
// []和{} 不包含null
const isObject = (obj) => typeof obj === 'object' && obj;
// []
const isArray = (arr) => Array.isArray(arr);
// {}
const isPlainObj = (obj) => isObject(obj) && !isArray(obj);
function _getCase(obj) {
if(!isObject(obj)) return null;
if(isArray(obj)) {
return obj.reduce((curr, next) => {
curr.push(_getCase(next));
return curr;
},[])
}
let result = {};
for(let key in obj) {
const value = obj[key];
const caseKey = keyToCase(key);
if(isObject(value)) {
result[caseKey] = _getCase(value);
return result;
}
result[caseKey] = value
}
return result;
}
return _getCase(obj);
}
2 数组转数
var arr3 = [
{
menuId: 1,
name: '系统管理1',
parentMenu: null
},
{
menuId: 2,
name: '系统管理2',
parentMenu: null
},
{
menuId: 3,
name: '系统管理1_0',
parentMenu: 1
},
{
menuId: 4,
name: '系统管理1_1',
parentMenu: 1
},
{
menuId: 5,
name: '系统管理2_0',
parentMenu: 2
},
{
menuId: 6,
name: '系统管理5_0',
parentMenu: 5
},
{
menuId: 7,
name: '系统管理3',
parentMenu: null
}
]
function arrToThree(arr) {
const parentList = arr.filter(item => !item.parentMenu);
const childList = arr.filter(item => item.parentMenu);
function foo(par, chil) {
par.forEach(ele => {
chil.forEach((item) => {
if(!ele.chilren) {
ele.chilren = [];
}
if(ele.menuId === item.parentMenu) {
ele.chilren.push(item)
}
})
if(ele.chilren && ele.chilren.length) {
foo(ele.chilren, childList)
}
});
}
foo(parentList, childList)
return parentList;
}
console.log(arrToThree(arr3))
3 数字千位格式化
1283543 --> 1,283,543
0.5432143144 --> 0.543,214,314,4
1343.8593218 --> 1,343.859,321,8
function format(num) {
if(typeof num !== 'number') return '';
const dotReg = /\./;
const reg = /\B(?=(\d{3})+\b)/g;
const numStr = num + '';
function strToReverse(str) {
if(typeof str !== 'string') return ''
return str.split('').reverse().join('')
}
if(dotReg.test(numStr)) {
const arr = numStr.split('.');
arr[0] = arr[0] ? arr[0].replace(reg, ',') : '';
const _temStr = strToReverse(arr[1]).replace(reg, ',')
arr[1] = arr[1] ? strToReverse(_temStr) : ''
return arr.join('.')
}
return numStr.replace(reg, ',');
}
console.log(format(1234329)) // 1,234,329
console.log(format(12343.2904365)) // 12,343.290,436,5
console.log(format(0.2904365)) // 0.290,436,5
深拷贝循环引用?
两个页面间实时通信
实现call方法