如何使用对象的属性作为变量?

时间:2014-03-14 04:55:56

标签: javascript

我试图让var dir= director引用属性"director":"Jean Rouch and Edgar Morin.",我该怎么做?我是Javascript的新手,请原谅我,如果我没有使用正确的条款。

 var myFavoriteDocumentary = {
    "name": "Chronicle of a Summer.",
        "reldate": "1961.",
        "language": "French.",
        "director": "Jean Rouch and Edgar Morin.",
        "getFavFilm": function () {
        return "My favorite non-fiction film is:" + "\n" + this.name + "\n" + "Directed by:" + "\n" + this.director + "\n" + "Year of film:" + "\n" + this.reldate + "\n" + "Language:" + "\n" + this.language;
    }
}
console.log(myFavoriteDocumentary.name);
console.log(myFavoriteDocumentary.getFavFilm());

var dir= "director"

        function dirFake(dir) {
            console.log("The directors are: " + dir);
            dir = "Vertov";
            console.log( dir + " is not the director" );
        }
        dirFake(dir);
        console.log( dir + " are the true directors!" );

3 个答案:

答案 0 :(得分:2)

您可以使用与控制台名称相同的步骤。

var dir=myFavoriteDocumentary.director;  

答案 1 :(得分:0)

如果你问我认为你在问什么,只需使用javascripts括号或点符号作为对象。

myFavoriteDocumentary.directory;
myFavoriteDocumentary["directory"];

答案 2 :(得分:0)

    var myFavoriteDocumentary = {
    "name": "Chronicle of a Summer.",
        "reldate": "1961.",
        "language": "French.",
        "director": "Jean Rouch and Edgar Morin.",
        "getFavFilm": function () {
        return "My favorite non-fiction film is:" + "\n" + this.name + "\n" + "Directed by:" + "\n" + this.director + "\n" + "Year of film:" + "\n" + this.reldate + "\n" + "Language:" + "\n" + this.language;
    }
}

console.log(myFavoriteDocumentary.name);
console.log(myFavoriteDocumentary.getFavFilm());

var dir = myFavoriteDocumentary.director;

    function dirFake(dir) {
        console.log("The directors are: " + dir);
        dir = "Vertov";
        console.log( dir + " is not the director" );
    }
    dirFake(dir);
    console.log( dir + " are the true directors!" );

抱歉日志显示以下结果的格式:

  

一个夏天的纪事。 VM178:11   我最喜欢的非小说类电影是:   一个夏天的纪事。   导演是:   Jean Rouch和Edgar Morin。   电影年份:   1961年。   语言:   法语。 VM178:12   董事是:Jean Rouch和Edgar Morin。 VM178:17   Vertov不是导演VM178:19   Jean Rouch和Edgar Morin。是真正的导演!   希望能回答你的问题。