Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lgwebdream opened this issue Jul 6, 2020 · 6 comments
Labels
JavaScript teach_tag 老虎 company

Comments

@lgwebdream
Copy link
Owner

No description provided.

@lgwebdream lgwebdream added JavaScript teach_tag 老虎 company labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

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

@523451928
Copy link

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

@GolderBrother
Copy link

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

@dty999
Copy link

dty999 commented Jul 7, 2021

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

}

@xingdongyu1994
Copy link

xingdongyu1994 commented Mar 15, 2022

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

@gaohan1994
Copy link

最直接的思路是使用闭包

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag 老虎 company
Projects
None yet
Development

No branches or pull requests

6 participants