FE-Interview
FE-Interview copied to clipboard
设计一个函数,奇数次执行的时候打印 1,偶数次执行的时候打印 2
扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

function test() {
test.count = test.count ? test.count+1 : 1
if (test.count % 2 === 0) {
console.log(2)
} else {
console.log(1)
}
}
test()
function countFn() {
let count = 0;
return function (...args) {
count++;
if (count & 1 === 1) return console.log(1);
console.log(2);
}
}
const testFn = countFn();
testFn(); // 1
testFn(); // 2
testFn(); // 1
testFn(); // 2
testFn(); // 1
testFn(); // 2
function* Print() {
while (true) {
yield console.log('1');
yield console.log('2');
}
}
let p = Print()
function myprint() {
p.next()
}
myprint()
myprint()
myprint()
}
let a = (function () {
let num = 0
return function () {
num++
return num % 2 === 0 ? 2 : 1
}
})()
最直接的思路是使用闭包
const oddEvenConsole = () => {
let count = 0;
return function () {
const isEven = count % 2 === 0;
console.log(isEven ? 2 : 1);
count++;
};
};