- 小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
因为现在大环境的原因,前端对底层原理需要有一定的掌握,所以特地学习并记录一下前端涉及到的各种手写及算法。 书接上文前端手写各种(三)
10.类数组转数组
// 扩展运算符
[...arrayLike];
// Array.from
Array.from(arrayLike);
// Arry.prototype.slice
Array.prototype.slice.call(arrayLike);
// array.apply
Array.apply(null, arrayLike);
// Array.prototype.concat
Array.prototype.concat.aaply([], arrayLike);
11.虚拟 DOM 转为真实 DOM
function _render(vnode) {
// 如果是数字类型转化为字符串
if (typeof vnode === "number") {
vnode = String(vnode);
}
// 字符串类型直接就是文本节点
if (typeof vnode === "string") {
return document.createTextNode(vnode);
}
// 普通DOM
const dom = document.createElement(vnode.tag);
if (vnode.attrs) {
// 遍历属性
Object.keys(vnode.attrs).forEach((key) => {
const value = vnode.attrs[key];
dom.setAttribute(key, value);
});
}
// 子数组进行递归操作
vnode.children.forEach((child) => dom.appendChild(_render(child)));
return dom;
}
12.手写轮播图
function $(id) {
return document.getElementById(id);
}
window.onload = function() {
var oLeft = $("left");
var oRight = $("right");
var index = 0;
var timer = null;
var pic = $("pic").getElementsByTagName("li");
var num = $("num").getElementsByTagName("li");
var oDiv = $("wrap");
oRight.onclick = function() {
index++;
if (index >= pic.length) {
index = 0;
}
change(index);
}
oLeft.onclick = function() {
index--;
if (index < 0) {
index = pic.length - 1;
}
change(index);
}
oDiv.onmouseover = function() {
clearInterval(timer);
}
oDiv.onmouseout = function() {
timer = setInterval(run, 2000); //鼠标移出后重新开始定时器
}
timer = setInterval(run, 4000); //定时器
function run() { //用于定时器的函数
index++;
if (index >= pic.length) {
index = 0;
}
change(index);
}
for (var i = 0; i < num.length; i++) {
num[i].index = i; //把索引值存起来
num[i].onmouseover = function() {
change(this.index);
}
}
function change(curindex) { //用于切换图片的函数
for (var i = 0; i < pic.length; i++) {
pic[i].style.display = "none";
num[i].className = "";
}
pic[curindex].style.display = "block";
num[curindex].className = "active";
index = curindex;
}
}
感兴趣的童鞋,可以继续关注后续文章。