javascript中变量中的变量

variables in variable in javascript

本文关键字:变量 javascript      更新时间:2023-09-26

在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>

但是,我无法打印所需的结果
提前谢谢。

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

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

最重要的是,您正试图从$(function() { ... });外部的访问data,到那时它已经不存在了。

$(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
  });

演示

从未听说过"自调用函数"?

var data = {
    GetAnimals: (function () {
            return 'tiger';
            // assign value to GetAnimals variable
        })(),
    GetBirds: (function () {
            return 'pegion';
            // assign value to GetBirds variable
        })()
}
});
$(function () {
   var data = {
        getAnimals: function() {
            return 'tiger';
        },
        getBirds: function() {
            return 'pigeon';  // I guess you meant pigeon
        }
    }
  });
  document.write(data.getAnimals()); // *call* the method
  document.write(data.getBirds()); // call the correct method

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