简体   繁体   中英

How to use the property of an object for a variable?

I'm trying to get the var dir= director to refer to the property "director":"Jean Rouch and Edgar Morin.", How can I do that? I'm new to Javascript, so pardon me if I don't use the right terms.

 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!" );

您可以使用用于控制台名称的相同过程。

var dir=myFavoriteDocumentary.director;  

If you're asking what I think you're asking, just use javascripts bracket or dot notation for objects.

myFavoriteDocumentary.directory;
myFavoriteDocumentary["directory"];
    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!" );

sorry for the formatting the log shows following result:

Chronicle of a Summer. VM178:11 My favorite non-fiction film is: Chronicle of a Summer. Directed by: Jean Rouch and Edgar Morin. Year of film: 1961. Language: French. VM178:12 The directors are: Jean Rouch and Edgar Morin. VM178:17 Vertov is not the director VM178:19 Jean Rouch and Edgar Morin. are the true directors! Hope that answers your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM