复制具有其属性的对象的函数?

时间:2013-01-06 14:51:42

标签: javascript function copy

我需要创建一个使用document.write复制和对象并输出所有对象属性的函数。

我创建了这样一个函数,但是我得到了[object Object],我无法理解为什么。

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <script type="text/javascript">
        /********* GLOBAL VARIABLES *********/
        var BR = "<br />";
        var ES = " ";



        /********* FUNCTIONS *********/


        function compare(album0, album1) {

            //This seems to do exactly what's needed... but sadly I dont have time to test every possible scenario.
            var sameTracks = true;
            for (var i = 0; i < album0.length; i++) {
                if (!(album0.tracks[i] === album1.tracks[i])) sameTracks = false;
            }
            for (var i = 0; i < album1.length; i++) {
                if (!(album0.tracks[i] === album1.tracks[i])) sameTracks = false;
            }

            if (
            album0.artistName === album1.artistName && album0.albumTitle === album1.albumTitle && album0.releaseYear === album1.releaseYear && album0.ifHQ === album1.ifHQ && album0.tracks.length === album1.tracks.length && sameTracks === true) {
                return true
            }
            else {
                return false
            };
        }


        function copy(album1) //the copy function
        {


            //properties will be copied over from original album1 into copy
            var albumCopy = 
            {
                artistName: "",
                albumTitle: "",
                releaseYear: 0,
                ifHQ: "",
                tracks: undefined
            };
            //copies original object values item for item into duplicate album
            for (var key in albumCopy) 

            {
            albumCopy[key] = album1[key];
            }
            return albumCopy;
        }


        /********* MAIN *********/
        function main() {

            var album = new Array(2)






            for (var i = 0; i < album.length; i++) //ok, so basically this loop is responsible for creating the album objects...
            {
                album[i] = {
                    artistName: "",
                    albumTitle: "",
                    releaseYear: 0,
                    ifHQ: "",
                    tracks: undefined //tracks here
                };

                album[i].artistName = prompt("What is the artist's name?");
                album[i].albumTitle = prompt("What is the album title?");
                album[i].releaseYear = parseFloat(prompt("What is the album's release year"));
                album[i].ifHQ = prompt("Is the album high quality? Y/N");

                while (!(album[i].ifHQ === "Y" || album[i].ifHQ === "N" || album[i].ifHQ === "YES" || album[i].ifHQ === "NO")) //to handle bad input
                {
                    album[i].ifHQ = prompt("You have entered an invalid response. Is " + album[i].title + " a ifHQ album, Y/N?");
                    album[i].ifHQ = album[i].ifHQ.toUpperCase();
                }

                if (album[i].ifHQ === "Y") {
                    album[i].ifHQ = true;
                }
                else {
                    album[i].ifHQ = false;
                }

                album[i].tracks = new Array(2); // the tracks property of each album object is an array of tracks... 

                for (var j = 0; j < album[i].tracks.length; j++) {
                    album[i].tracks[j] = prompt("Enter track " + (j + 1));
                }
            }

            for (var key in album[0]) //and these for... in loops navigate through properties for these objects to output what was stored in them
            {
                document.write(key + ": " + album[0][key] + " ");
                document.write(BR);
            }
            for (var key in album[1]) {
                document.write(key + ": " + album[1][key] + " ");
                document.write(BR);
            }

            var same = compare(album[0], album[1]);
            document.write("The status of both albums being identical is" + ES + same + BR);
            var copiedAlbum = copy(album[1]);
            document.write(copiedAlbum);
        }



        // This line calls main, don't change it:
        main();







    </script>
</body>

2 个答案:

答案 0 :(得分:0)

要复制对象,可以使用Object.create方法,然后可以使用for in循环对象,并可以使用document.write输出属性,例如,您可以使用

// For older browser's suppoet
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

// an object
var album1={
    artistName: "",
    albumTitle: "",
    releaseYear: 0,
    ifHQ: "",
    tracks: undefined
};
// create a new object from album1/copy
var newAlbum=Object.create(album1);
// output the properties
for(var i in newAlbum) document.write(i+'<br />');

Example

答案 1 :(得分:0)

作为对我的评论的跟进,这是一个更好的方式来做你正在尝试做的事情:

// This code defines an "Album" class
function Album(artistName, albumTitle, releaseYear, ifHQ) {
    this.artistName = artistName;
    this.albumTitle = albumTitle;
    this.releaseYear = releaseYear;
    this.ifHQ = ifHQ;
    this.tracks = [];
};

// Album.prototype contains all methods available to Album objects
Album.prototype.addTrack = function(trackName) {
    this.tracks.push(trackName);
};

// alternative to compare() function
Album.prototype.equals = function(album) {
    if (this.artistName != album.artistName) return false;
    if (this.albumTitle != album.albumTitle) return false;
    if (this.releaseYear != album.releaseYear) return false;
    if (this.tracks.length != album.tracks.length) return false;

    for (var i = 0, len = this.tracks.length; i < len; i++) {
        if (this.tracks[i] != album.tracks[i]) return false;
    }

    return true;
};

// create our own custom toString method
Album.prototype.toString = function() {
    var str = "";
    str += "Artist: " + this.artistName;
    str += "Album: " + this.albumName;
    // you get the idea
    return str;
};



// MAIN
// create albums
var albums = []

var queen = new Album("Queen", "Queen", 1973, true);
var queen2 = new Album("Queen", "Queen II", 1974, true);
albums.push(queen, queen2);

var albumsAreTheSame = queen.equals(queen2); // test if queen == queen2

document.write(queen); // queen.toString() is automatically called

此代码显然不完整