FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

设计一个函数,奇数次执行的时候打印 1,偶数次执行的时候打印 2

Open lgwebdream opened this issue 4 years ago • 6 comments

lgwebdream avatar Jul 06 '20 15:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 15:07 lgwebdream

function test() {
  test.count = test.count ? test.count+1 : 1
  if (test.count % 2 === 0) {
    console.log(2)
  } else {
    console.log(1)
  }
}
test()

523451928 avatar Jul 16 '20 06:07 523451928

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

GolderBrother avatar Sep 06 '20 09:09 GolderBrother

function* Print() {
  while (true) {
    yield console.log('1');
    yield console.log('2');
  }
}
let p = Print()
function myprint() {
  p.next()
}
myprint()
myprint()
myprint()

}

dty999 avatar Jul 07 '21 13:07 dty999

let a = (function () {
	let num = 0
	return function () {
		num++
		return num % 2 === 0 ? 2 : 1
	}
})()

xingdongyu1994 avatar Mar 15 '22 07:03 xingdongyu1994

最直接的思路是使用闭包

const oddEvenConsole = () => {
  let count = 0;
  return function () {
    const isEven = count % 2 === 0;
    console.log(isEven ? 2 : 1);
    count++;
  };
};

gaohan1994 avatar Apr 28 '24 04:04 gaohan1994