1. 实现每隔一秒打印1234
可以使用es6的let 也可以使用var+立即执行函数
function print() {
for (let i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i)
},1000 * i)
}
}
print()
// 或者是下面这样
function print() {
for (var i = 0; i < 5; i++) {
(function (i) {
setTimeout(() => {
console.log(i)
}, 1000 * i)
})(i)
}
}
print()
2. 循环打印红黄绿
下面来看一道比较典型的问题,通过这个问题来对比几种异步编程方法:红灯 3s 亮一次,绿灯 1s 亮一次,黄灯 2s 亮一次;如何让三个灯不断交替重复亮灯?
方法一 使用 callback
const task = (timer, light, callback) => {
setTimeout(() => {
if (light === 'red') {
console.log('red');
} else if (light === 'green') {
console.log('green');
} else if (light === 'yellow') {
console.log('yellow');
}
callback()
},timer)
}
// task(3000, 'red', () => {
// task(2000, 'green', () => {
// task(1000,'yellow', Function.prototype)
// })
// })
const step = () => {
task(3000, 'red', () => {
task(2000, 'green', () => {
task(1000,'yellow', step)
})
})
}
step()
方法二 使用 promise
function task(timer,light) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (light === 'red') {
console.log('red');
} else if (light === 'green') {
console.log('green');
} else if (light === 'yellow') {
console.log('yellow');
}
resolve()
},timer)
})
}
这个是使用promise
const step = () => {
task(3000, 'red')
.then(() => task(2000, 'green'))
.then(() => task(1000, 'yellow'))
.then(step)
}
step()
方法三 async await
function task(timer,light) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (light === 'red') {
console.log('red');
} else if (light === 'green') {
console.log('green');
} else if (light === 'yellow') {
console.log('yellow');
}
resolve()
},timer)
})
}
const taskRunner = async () => {
await task(3000, 'red')
await task(2000, 'green')
await task(2100, 'yellow')
taskRunner()
}
taskRunner()
3. 实现jsonp
jsonp是利用js中对script标签里面的url可以进行跨域访问的操作
// 动态加载js文件
function addScript(src) {
const script = document.createElement('script');
script.src = src;
script.type = "text/javascript";
document.body.appendChild(script);
}
addScript("http://xxx.xxx.com/xxx.js?callback=handleRes")
function handleRes(res) {
console.log(res);
}
handleRes({a:1,b:2})
4. js对象转换成树
// 转换前:
data = [
{ id: 1, pid: 0, name: 'body' },
{ id: 2, pid: 1, name: 'title' },
{ id: 3, pid: 2, name: 'div' }
]
// 转换为:
tree = [{a
id: 1,
pid: 0,
name: 'body',
children: [{
id: 2,
pid: 1,
name: 'title',
children: [{
id: 3,
pid: 2,
name: 'div'
}]
}
}]
function jsonToTree(data) {
let result = []
if (!Array.isArray(data)) {
return result;
}
let map = {}
data.forEach(item => {
map[item.id] = item
})
// console.log(map)
// {
// '1': { id: 1, pid: 0, name: 'body' },
// '2': { id: 2, pid: 1, name: 'title' },
// '3': { id: 3, pid: 2, name: 'div' }
// }
data.forEach(item => {
let parent = map[item.pid]
if (parent) {
(parent.children || (parent.children = [])).push(item)
} else {
result.push(item);
}
})
return result
}
jsonToTree(data)