如果此代码运行,请执行代码

Do code if this code runs

本文关键字:代码 执行 运行 如果      更新时间:2023-09-26

如果运行了另一个代码片段,我想运行代码。

IF此代码运行

(function() {
// Code runs here
})();

THEN同时运行此代码

//This code

示例

if (condition) {
    block of code to be executed if the condition is true
}

http://www.w3schools.com/js/js_if_else.asphttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/if...else

这似乎行不通?

if ((function() {// Code runs here})();) 
    {
        //This code
    }

您应该使用return语句,否则IIFE将返回undefined,因此它将等效于false语句。

if (
(function() {
   // Code runs here
   return true;
})();
){
  //This code
}

使用此

var functionName = (function() {
  var didRun = false;
  // This function will be executed only once, no matter how many times
  // it is called.
  function functionName() {
    // Your code goes here
  }
  return function() {
    if (didRun) {
      return;
    }
    didRun = true;
    return foo.apply(this, arguments);
  }
})();

并检查,当函数didRun时,然后执行您的核心

IIFE在这里对我来说似乎是多余的——只需以简单的方式使用命名函数并保持它的直接性。如果有人能给我一个IIFE作为If。。。否则,请评论-我很想了解我可能错过了什么:

function odd(num) {
  return num % 2;
}
// Use Dev Tools Console (F12) to see output
function logOddEven(num) {
  if (odd(num)) {
    console.log(num + ' is odd');
  } else {
    console.log(num + ' is even');
  }
}
logOddEven(0);
logOddEven(1);
logOddEven(2);