繁体   English   中英

Javascript:构造函数类的打印数组

[英]Javascript: Printing array of a constructor class

仅张贴所需的零件。

    // This program simulates purchases of musical albums through a loop. 
// The user initially has 1000 dollars. As the program loops through the albums
// the user purchases random quantities. The program adds the subtotals and 
// subtracts from the initial total to find out what the user has left. 

// Variables for random quantity. 
var min = 1,
    max = 25;

// Constructor for Album class
function Album(title, artist, price, release){
    this.title = title;
    this.artist = artist;
    this.price = price;
    this.release = release;
    this.quantity = (Math.floor(Math.random() * max) + min);
    this.subtotal = this.quantity * this.price;

};
Album.prototype.purchase = function(){
    this.quantity--;
    if (this.quantity > 0){
        return 1;
    }
    else{
        return -1;
    }
};

// Constructor for Cart class
function Cart(val){
    this.items = [];
};

Cart.prototype.add = function(val){
    this.items.push(val);
};

Cart.prototype.remove = function(val){
    this.items.splice(albums.indexOf(val), 1);
};

// Object that inherit from the Album class.
var nothingSame = new Album('Nothing Was the Same', "Drake", 15.99, "09/24/2013");
nothingSame.tracklisting = ["Started from the Bottom", "All Me", "Pound Cake", "The Language"];

var lifeOfPablo = new Album("The Life of Pablo", "Kanye West", 15.98, "02/14/2016");
lifeOfPablo.tracklisting = ["Ultralight Beam", "Famous", "Feedback", "Low Lights"];

var babel = new Album("Babel", "Mumford & Sons", 13.83, "09/21/2012");
babel.tracklisting = ["I Will Wait", "Lover of the Light", "Whispers in the Dark", "Babel"];

var ghostStories = new Album("Ghost Stories", "Coldplay", 12.61, "05/16/2014");
ghostStories.tracklisting = ["Magic", "Midnight", "A Sky Full of Stars", "True Love"];

var trueAlbum = new Album("True", "Avicii", 15.99, "09/13/2013");
trueAlbum.tracklisting = ["Wake Me Up", "You Make Me", "Hey Brother", "Lay Me Down"];

// Array of the albums for the objects within them.
var albums = [nothingSame, lifeOfPablo, babel, ghostStories, trueAlbum];

//Variables the initial amount of money
var INITIAL_MONEY = 1000.00;
var n = 1000.00;

// Instance of cart.
var cart = new Cart();

// Loop that simulates the purchase. 
var i = 0;
while(INITIAL_MONEY > 0 && i < albums.length){
    if (INITIAL_MONEY >= albums[i].subtotal){
        albums[i].purchase();
        INITIAL_MONEY = INITIAL_MONEY - albums[i].subtotal;
        cart.add(albums[i]);
    }
    i++;
}

// Variable for the total amount spent.
var total = n - INITIAL_MONEY;

// Console logs to output all the data to the user. 
console.log("You walk into a store with $1000 and purchase several albums.")
console.log(cart);
console.log("Total: " + total.toFixed(2));
console.log("Money Remaining: " + INITIAL_MONEY.toFixed(2));

输出示例:

You walk into a store with $1000 and purchase several albums.
Cart {
  items: 
   [ Album {
       title: 'Nothing Was the Same',
       artist: 'Drake',
       price: 15.99,
       release: '09/24/2013',
       quantity: 22,
       subtotal: 367.77,
       tracklisting: [Object] },
     Album {
       title: 'The Life of Pablo',
       artist: 'Kanye West',
       price: 15.98,
       release: '02/14/2016',
       quantity: 1,
       subtotal: 31.96,
       tracklisting: [Object] },
     Album {
       title: 'Babel',
       artist: 'Mumford & Sons',
       price: 13.83,
       release: '09/21/2012',
       quantity: 1,
       subtotal: 27.66,
       tracklisting: [Object] },
     Album {
       title: 'Ghost Stories',
       artist: 'Coldplay',
       price: 12.61,
       release: '05/16/2014',
       quantity: 4,
       subtotal: 63.05,
       tracklisting: [Object] },
     Album {
       title: 'True',
       artist: 'Avicii',
       price: 15.99,
       release: '09/13/2013',
       quantity: 18,
       subtotal: 303.81,
       tracklisting: [Object] } ] }
Total: 794.25
Money Remaining: 205.75

我不知道如何显示曲目列表。 我最接近它,它只显示了所有阵列中的最后一个轨道。 我似乎无法让每个专辑都在输出中显示列出的曲目。

手动遍历相册实例的tracklisting属性,可以获取各个项目:

 // Loop over the albums array
 for(var i = 0; i < albums.length; ++i){
     // Loop through the tracklisting array elements for the current album
     for(var x = 0; x < albums[i].tracklisting.length; ++x){
        console.log(albums[i].tracklisting[x]);
     }
 }

但是,如何:

   var albumString = JSON.stringify(albums);
   console.log(albumString);

要将整个对象结构简单地转换为字符串?

如果您只想将创建的对象的内容转储到控制台,那么这不是js问题,而是更多地处理您正在使用的控制台的怪癖...例如,某些控制台会折叠嵌套的对象。

在大多数情况下,您可以将对象转储到字符串并输出,这是一个很好的调试方法(从控制台调用执行开始,它还为您提供了对象的视图,而不是对稍后可能更改的对象的引用):

JSON.stringify(albums);

因此在典型的控制台调用中:

console.log(JSON.stringify(albums));

如果要出于调试或toString目的而输出,可以尝试JSON.stringify(albums, null, 2)

如果要在控制台中显示它,请使用console.log ,尝试console.log(JSON.stringify(albums, null, 2))

编辑:

应用于您的Cart实现时,请使用console.log(JSON.stringify(cart, null, 2))代替console.log(cart)

样品输出

{
  "items": [
    {
      "title": "Nothing Was the Same",
      "artist": "Drake",
      "price": 15.99,
      "release": "09/24/2013",
      "quantity": 18,
      "subtotal": 303.81,
      "tracklisting": [
        "Started from the Bottom",
        "All Me",
        "Pound Cake",
        "The Language"
      ]
    },
    {
      "title": "The Life of Pablo",
      "artist": "Kanye West",
      "price": 15.98,
      "release": "02/14/2016",
      "quantity": 15,
      "subtotal": 255.68,
      "tracklisting": [
        "Ultralight Beam",
        "Famous",
        "Feedback",
        "Low Lights"
      ]
    },
    {
      "title": "Babel",
      "artist": "Mumford & Sons",
      "price": 13.83,
      "release": "09/21/2012",
      "quantity": 16,
      "subtotal": 235.11,
      "tracklisting": [
        "I Will Wait",
        "Lover of the Light",
        "Whispers in the Dark",
        "Babel"
      ]
    },
    {
      "title": "True",
      "artist": "Avicii",
      "price": 15.99,
      "release": "09/13/2013",
      "quantity": 10,
      "subtotal": 175.89000000000001,
      "tracklisting": [
        "Wake Me Up",
        "You Make Me",
        "Hey Brother",
        "Lay Me Down"
      ]
    }
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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