笔试--2023-3-16

本文介绍了几种JavaScript数据处理方法,包括将下划线命名转换为小驼峰命名的函数,深拷贝对象以保留原数据结构,展平嵌套数组以及将对象拼接成树形结构。同时讨论了不同方法可能遇到的问题及解决方案,并提到了检测package.json中循环依赖的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 实现下划线转小驼峰
    链接
// 方法一:JSON.stringify
function toUpper(obj){
	let str = JSON.stringify(obj)
	const res = str.replace(/\_(\w)/g,(val)=>val[1].toUpperCase())
	return JSON.parse(res) 
}
// 问题:1.undefined,函数,symbol会被忽略  
//  	2.Number,String,Boolean类型会被转成初始值  
//		3.不可枚举属性会被忽略
// 方法二:深拷贝
function clone(obj){
	if(obj === null)return null
	if(typeof obj === 'object')return obj
	if(obj instanceof RegExp)return new RegExp(obj)
	if(obj instanceof Date)return new Date(obj)
	const cloneObj = new obj.constructor()
	for(let key in obj){
		if(!obj.hasOwnProperty(key))break
		const str = key.replace(/\_(\w)/g,(val)=>val[1].toUpperCase())
		cloneObj[str] = clone(obj[key])
	}
	return cloneObj
}
  1. 展平数组
// 方法1:使用字符串的toString
function test(arr){
    return arr.toString().split(',')
}
//	问题:  1.所有数据类型转换为字符串,如'function Date() {...}','()=>{...}'
//			2.undefined,null,[] 会转换成空字符串
//			3.Number,String,Boolean类型会被转成初始值
//			4.对象转化为 '[object Object]'
// 方法二:递归
function flat(val) {
    let res = []
    function test(arr) {
        arr.forEach((item) => Array.isArray(item) ? test(item) : (res.push(item)))
    }
    test(val)
    return res
}

// 测试数组
const arr = [1, Date, [undefined, false, [null, {}, [], 2n, [Number(1), Boolean(true), [9], 11], 12], 13], 14]
  1. 对象拼接成树(多棵树,二级结构无children)
function objToTree(arr) {
    const res = []
    const roots = arr.filter(item => item.pid === 0)
    function format(node, arrList) {
        const children = arrList
            .filter(val => val.pid === node.id)
            .map(item => format(item, arrList))
        return {...node, children}
    }
    roots.forEach(item => res.push(format(item,arr)))
    return res
}
// 测试数组
//const treeArr = [
//     {pid: 0, id: 1, label: 'a'},
//     {pid: 1, id: 2, label: 'a'},
//     {pid: 1, id: 3, label: 'a'},
//     {pid: 0, id: 4, label: 'a'},
//     {pid: 3, id: 5, label: 'a'},
//     {pid: 0, id: 6, label: 'a'},
// ]
  1. 实现 检测 package.json 数据有无依赖循环
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳晓黑胡椒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值