当前位置:  开发笔记 > 编程语言 > 正文

即时创建Javascript对象

如何解决《即时创建Javascript对象》经验,为你挑选了1个好方法。

我相信我已经在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"?

可以给我正在寻找的这类功能一个名字吗?

谢谢.



1> Justin Johns..:

这就是发生的事情:

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;
}

阅读此处了解有关对象文字的更多信息.

推荐阅读
pan2502851807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有