为什么我必须IF返回,IF什么?



我正在学习编码,或者更确切地说-甚至在这一刻阅读代码。谁能给我解释一下,为什么会有这些线,它们是做什么的?

if (noClicking) return;
if (e.target.classList.contains("flipped")) return;

这两行的目的是什么?

function handleCardClick(e) {
// you can use event.target to see which element was clicked
if (noClicking) return;
if (e.target.classList.contains("flipped")) return;
let currentCard = e.target;
currentCard.style.backgroundColor = currentCard.classList[0];
if (!card1 || !card2) {
currentCard.classList.add("flipped");
card1 = card1 || currentCard;
card2 = currentCard === card1 ? null : currentCard;
}
if (card1 && card2) {
noClicking = true;
// debugger
let gif1 = card1.className;
let gif2 = card2.className;
if (gif1 === gif2) {
cardsFlipped += 2;
card1.removeEventListener("click", handleCardClick);
card2.removeEventListener("click", handleCardClick);
card1 = null;
card2 = null;
noClicking = false;
} else {
setTimeout(function() {
card1.style.backgroundColor = "";
card2.style.backgroundColor = "";
card1.classList.remove("flipped");
card2.classList.remove("flipped");
card1 = null;
card2 = null;
noClicking = false;
}, 1000);
}
}
if (cardsFlipped === COLORS.length) alert("game over!");
}
if (noClicking) return;
if (e.target.classList.contains("flipped")) return;

如果返回其中一行,则不执行这两行以下的行。这意味着如果noClicking == truee.target.classList.contains("flipped") == true,那么这2行以下的所有行都不会被执行。

虽然已经给出的答案是正确的,但我认为它可以帮助理解为什么那些线就在那里。它们被称为保护条款。它们的目的是使你的代码更高效。

想象这样一个场景:

function myFunc(someParam) {
/*
do something that takes a lot of time/resources
... then somewhere you find someParam was invalid!
so all the calculations done until now was useless
*/
}

所以,当你在函数中需要参数、全局变量等时,不是检查它们的有效性,而是在函数开始时检查它们,就像这样:

function myFunc(someParam) {
//let's say valid() is a function that checks for validity of the param,
//returns true if valid, false if invalid.
if(!valid(someParam)) return;
/*
do something that takes a lot of time/resources
... then your function will only run the expensive code
if it is sure that there are no invalid arguments passed to it.
*/
}

不一定只有return。这是你的选择。也许函数总是返回一些正数,那么您可以这样return -1:

const getRoot = (num) => {
if(num < 0) return -1;
//get square root of the number
return abs(Math.sqrt(num));
}
//Then when you call the function, you could check if the result is not -1,
//to make sure you passed the correct arguments.
if (getRoot(-1) < 0) 
console.error("Uh oh, you passed a negative number to the square root function");

或者你可以抛出Error:


function myFunc (someParam) {
if(!valid(someParam)) throw new Error("wrong param bruh");
//do something...
}

最新更新