如何使用字典在 JavaScript return 值中实现回调

How to Implement a Callback in JavaScript return Value with a Dictionary

我正在尝试实现一个具有键和值的 JS 字典,其中值调用回调函数进行验证。

例如,我尝试定义一个 animalsDict 字典。 当我尝试调用“Dog”键来调用值 validateDogSound() 回调函数时,bootbox.alert 没有显示。

我做错了什么?这是我们在字典中做回调函数的方式吗?任何提示或帮助?谢谢

var animalsDict = {
    Dog: validateDogSound(),
  //Cat: validateCatSound(), 
  //Bird: ... etc
}

function validateDogSound(){
 bootbox.alert("dogs bark!");  
 return false;
}

console.log('testDog', animalsDict["Dog"]);

您需要调用函数:

console.log('testDog', animalsDict["Dog"]());
//                                       ^

也把对象改成

var animalsDict = {
    Dog: validateDogSound,
  //Cat: validateCatSound, 
  //Bird: ... etc
}

这样


// "functions" first !

var validateDogSound = function()  
  {
  bootbox.alert("dogs bark!");  
  return false;
  }


var animalsDict = {
    Dog: validateDogSound ,  // no parenthesis
  //Cat: validateCatSound , 
  //Bird: ... etc
}
console.log('testDog', animalsDict["Dog"]() );  // with parenthesis

根据documentation,您需要按以下顺序加载javascript个库。

Since Bootbox is a wrapper around Bootstrap's modal functionality, you need to include the libraries in order:

jQuery
Popper.js
Bootstrap
Bootbox
Bootbox Locales (optional - omit if you only need the default English locale)

尝试以相同的顺序添加这些 header 或使用以下内容。我在 header 中添加了以下内容,看起来它起作用了。你会知道得更多。 请注意,我还没有验证这些 url,这只是为了演示。如果你的服务器上有这些的本地副本,并且在 head 中适当引用,那就更好了。

<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.5.2/bootbox.min.js"></script>
</head>
<body>
<script>
var animalsDict = {
    Dog: validateDogSound(),
  //Cat: validateCatSound(), 
  //Bird: ... etc
}

function validateDogSound(){
 bootbox.alert("dogs bark!");  
 return false;
}

console.log('testDog', animalsDict["Dog"]);
</script>

</body>
</html>