前端面试手写题系列 III

前端面试手写题系列 III

前端面试 手写题系列 已经完结,包含了以下的题目:

手写拍平数组 flat
手写防抖和节流函数
手写深拷贝
手写快排
手写 call、apply、bind
手写一个 sleep 函数
手写冒泡排序
函数柯里化
对象扁平化
手写 new 过程
求数组中的最大值
手写 instanceof
手写 foreach 函数
手写迭代器
手写 filter
实现一个 compose 函数
正则相关(去哪儿原题)
实现一个任务调度函数(得物原题)
数组转化为 tree
不使用 a 标签,实现 a 标签的功能
手写插入排序
LRU 算法
归并排序
求两个数组的交集、并集、补集、差集
提取 url 中的参数
实现一个洗牌函数 shuffle
希尔排序

1.数组转化为 tree

目的:

给你一个数组,其中包含了很多个对象,每一个对象中都有一个 key 叫做 parent,其为一个数值,这个数值代表的是它所在的层级,请把这个数组转变为树,-1表示的最顶层的节点

实现:

	<script>
		let arr = [
			{ id: 0, name: '1', parent: -1, childNode: [] },
			{ id: 1, name: '1', parent: 0, childNode: [] },
			{ id: 99, name: '1-1', parent: 1, childNode: [] },
			{ id: 111, name: '1-1-1', parent: 99, childNode: [] },
			{ id: 66, name: '1-1-2', parent: 99, childNode: [] },
			{ id: 1121, name: '1-1-2-1', parent: 112, childNode: [] },
			{ id: 12, name: '1-2', parent: 1, childNode: [] },
			{ id: 2, name: '2', parent: 0, childNode: [] },
			{ id: 21, name: '2-1', parent: 2, childNode: [] },
			{ id: 22, name: '2-2', parent: 2, childNode: [] },
			{ id: 221, name: '2-2-1', parent: 22, childNode: [] },
			{ id: 3, name: '3', parent: 0, childNode: [] },
			{ id: 31, name: '3-1', parent: 3, childNode: [] },
			{ id: 32, name: '3-2', parent: 3, childNode: [] }
		]

		function arrToTree(arr, parentId) {
			// 判断是否是顶层节点,如果是就返回。不是的话就判断是不是自己要找的子节点
			const filterArr = arr.filter(item => {
				return parentId === undefined ? item.parent === -1 : item.parent === parentId 
			})

			// 进行递归调用把子节点加到父节点的 childNode里面去
			filterArr.map(item => {
				item.childNode = arrToTree(arr, item.id)
				return item
			})

			return filterArr
		}

		arrToTree(arr)
	</script>

2.不使用 a 标签,实现 a 标签的功能

其实这里有一个面试题,会问就是说如果 html 中只有 div 标签的话,是不是依然能够正常作用,也就是说没有 header main a p h 等标签,只用 div 标签,是否能够正常实现页面?
答案肯定可以的,这个题目就是教你如何使用 div 实现 a 标签的功能。

目的:

使用 div 标签实现 a 标签的功能。

实现:

	<div onclick="window.open('index.html')"></div>
	<div onclick="window.location='index.html'"></div>
	<div onclick="window.location.replace('index.html')"></div>

3.手写插入排序

原理图解:

实现:

// 插入排序
//  
function insertSort(arr) {
    for (let i = 1; i < arr.length; i++) {
        let index = i
        let temp = arr[i]
        while (index > 0 && arr[index - 1] > temp) {
            index--
        }
        arr.splice(i, 1)
        arr.splice(index, 0, temp)
    }
}

// 测试
let arr = [2, 1, 3, 4]
insertSort(arr)
console.log(arr)

手写题系列文章

前端手写题系列 I
前端手写题系列 II
前端手写题系列 III
前端手写题系列 IV
前端手写题系列 V
前端手写题系列 VI
前端手写题系列 VII
前端手写题系列 VIII
前端手写题系列 IX
前端手写题系列 X

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

城南顾北

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

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

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

打赏作者

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

抵扣说明:

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

余额充值