我相信我已经在jquery中看到了一些这样的例子.但对我来说,以下代码不起作用.firebug调试器告诉我:'位置未定义'.你能告诉我这是否可行?
function ResolveGeoCode() { var Location; Location.Ad1 = "Hello "; Location.Ad2 = "World"; return Location; } var loc = ResolveGeoCode(); var String1 = loc.Ad1; //This contains "Hello "? var String2 = loc.Ad2; //This contains "World"?
可以给我正在寻找的这类功能一个名字吗?
谢谢.
这就是发生的事情:
function ResolveGeoCode() { // Location is declared, but its value is `undefined`, not `object` var Location; alert(typeof Location); // <- proof pudding // Failing here because you're trying to add a // property to an `undefined` value Location.Ad1 = "Hello "; Location.Ad2 = "World"; return Location; }
Location
在尝试向其添加属性之前,通过将其声明为空对象文字来修复它:
function ResolveGeoCode() { var Location = {}; alert(typeof Location); // now it's an object // Programmatically add properties Location.Ad1 = "Hello "; Location.Ad2 = "World"; return Location; }
如果您提前知道属性及其相应的值,则可以使用更内联的方法:
function ResolveGeoCode() { var Location = { Ad1: "Hello ", Ad2: "World" }; // ...further manipulations of Location here... return Location; }
阅读此处了解有关对象文字的更多信息.