Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中变量中的变量_Javascript_Jquery - Fatal编程技术网

javascript中变量中的变量

javascript中变量中的变量,javascript,jquery,Javascript,Jquery,在script标记中,为了在变量中检索变量值,我使用了以下代码,但它不返回任何值 <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <script type="text/javascript" language="javascript"> $(function () { var data = { GetAnimals: f

在script标记中,为了在变量中检索变量值,我使用了以下代码,但它不返回任何值

    <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    <script type="text/javascript" language="javascript">
    $(function () {
       var data = {
        GetAnimals: function()
        {
        return 'tiger';         assign value to GetAnimals variable
        },
        GetBirds:function()
        {
        return 'pegion';       assign value to GetBirds variable
        }
        }
      });

      document.write(data.GetAnimals);//should print tiger
      document.write(data.GetAnimals);//should print pegion

      </script>

$(函数(){
风险值数据={
GetAnimals:function()
{
返回'tiger';为GetAnimals变量赋值
},
GetBirds:function()
{
返回'pegion';为GetBirds变量赋值
}
}
});
document.write(data.GetAnimals)//应该印老虎吗
document.write(data.GetAnimals)//你应该打印佩吉恩
但是,我无法打印所需的结果。

提前感谢。

您没有将函数作为函数调用:

document.write(data.GetAnimals());//should print tiger
document.write(data.GetBirds());//should print pegion
最重要的是,您试图从外部
$(function(){…})访问
数据
,到那时已经不存在了

$(function () {
    var data = {
      GetAnimals: function() {
        return 'tiger'; //        assign value to GetAnimals variable
      },
      GetBirds:function() {
        return 'pegion'; //      assign value to GetBirds variable
      }
    }

    document.write(data.GetAnimals());//should print tiger
    document.write(data.GetBirds());//should print pegion
  });
从未听说过“自调用函数”吗

$(函数(){
风险值数据={
getAnimals:function(){
返回“老虎”;
},
getBirds:function(){
返回“鸽子”;//我猜你指的是鸽子
}
}
});
document.write(data.getAnimals());//*调用*方法
document.write(data.getBirds());//调用正确的方法

请使用适当的大小写和缩进。

我猜
数据
有局部范围???@sachin谢谢,你是对的,但是当代码包含在jquey中时,它就不起作用了。我想在我的上下文中使用jquery中包含的代码。@BharathKumar我已经更新了答案;您在范围方面有另一个问题。
var data = {
    GetAnimals: (function () {
            return 'tiger';
            // assign value to GetAnimals variable
        })(),
    GetBirds: (function () {
            return 'pegion';
            // assign value to GetBirds variable
        })()
}
});