簡體   English   中英

JavaScript - 如何打印對象中的所有值

[英]JavaScript - how to print all values from an object

我正在嘗試從此數組中獲取一個對象並將其所有值打印到一個 div 中,是否可能

function Car(company, name, price, details, image, alt){ 
        this.company = company;
        this.name = name;
        this.price = price;
        this.details = details;
        this.image = image;
        this.alt = alt;
    }

var carInformation = [new Car("Company: Ferrari", "Name: Marenello", "Price: $250,000", "Details: Fast. Very Fast.", "images/ferrari.jpg","image of ferrari"),
                          new Car("Company: Dodge", "Name: Viper", "Price: $100,000","Details: Great Acceleration","images/dodge.jpg", "image of viper"),
                          new Car("Company: Ford", "Name: Shelby", "Price: $80,000", "Details: Muscle Car", "images/mustang.jpg", "image of mustang"),
                          new Car("Company: Back To The Future", "Name: Delorean", "Price: $20,000", "Details: Travels through time","images/delorean.jpg", "image of delorean"),
                          new Car("Company: Lamborghini", "Name: Diablo", "Price: $250,000", "Details: Fastest","images/lambo.jpg","image of lamborghini"),
                          new Car("Company: Mercedes Benz", "Name: SLR", "Price: $180,000", "Details: Classy Vehicle.","images/benz.jpg","image of mercedes benz"),
                          new Car("Company: Chevrolet", "Name: Corvette", "Price: $70,000", "Details: Fiberglass body Light Vehicle.","images/vette.jpg","image of corvette"),
                          new Car("Company: Porsche", "Name: Carrera", "Price: $120,000", "Details: Great Handling.","images/porsche.jpg", "image of porsche"),
                          new Car("Company: Audi", "Name: R8", "Price: $110,000", "Details: Fast and Classy.", "images/audi.jpg","image of audi") ];

    for(i=0;i<carInformation.length;i++) {
    $('#container').append('<div class="product"><li><a href="#" ><img src="' + carInformation[i].image + '" alt="' + carInformation[i].alt +'" ></img></a></li><div class="description"><p class="carCompany">'+ carInformation[i].company +'</p><p class="carName">'+ carInformation[i].name +'</p><p class="carPrice">'+ carInformation[i].price +'</p><p class="carDetails">'+ carInformation[i].details +'</p></div></div>');
    $('#productPage').append('<div id="carInfo">' + carInformation[i] + '</div>');

        }

'#container' 行有效。 是否可以只打印所有值而不寫入每個屬性? 就像我在“#productPage”中嘗試過的一樣? 它返回對象對象。 為什么? 當我寫 console.log(carInformation[0]); 我能夠看到對象中的所有值。

carInformation[i] 是一個對象。 你能做的最好的事情是,向你的汽車添加一個原型方法,這樣它就會溢出所有的屬性,然后它可以在 div 中呈現。

function view(){
return "Company " + this.company + ",Name   " + this.Name + ", Price " + this.price ;
}


Car.prototype.view = view;

//and then use it inside div
 $('#productPage').append('<div id="carInfo">' + carInformation[i].view + '</div>');

您可以通過渲染 HTML 而不是純字符串來控制汽車信息的顯示方式。

試試這個,看看魔法:

alert(JSON.stringify(carInformation[0]));

您需要創建一些函數來將變量寫入 div。 您可以將這些添加到Car的原型中。

function Car(company, name, price, details, image, alt){ 
    this.company = company;
    this.name = name;
    this.price = price;
    this.details = details;
    this.image = image;
    this.alt = alt;
    }

Car.prototype.product = function() {
    return '<li><a href="#"><img src="'+this.image +'"alt="'+this.alt+'"></img></a></li>';
    };

Car.prototype.description = function() {
    return '<p class="carCompany">'+this.company+'</p><p class="carName">'+this.name +'</p><p class="carPrice">'+ this.price +'</p><p class="carDetails">'+ this.details +'</p>';
    };

然后您可以調用對象上的函數來填充您的 div。

 for(i=0;i<carInformation.length;i++) {
    $('#container').append('<div class="product">'+carInformation[i].product()+'<div class="description">' + carInformation[i].description() + '</div></div>');
    }

對於初學者:

var car = new Car( ... );
var $ul = $("<ul></ul>");
for(var key in car) {
  $ul.append("<li>" + car[key] + "</li>");
}
$('#container').append($ul);

您可以通過迭代對象來獲取所有屬性:我想,在其他情況下您也會打印您的對象,我認為,這是一個很好的解決方案 - 迷你模板:)

Car.prototype.view = function( template, separator ) {
  var arr=[], template = template || "<%name%>: <%value%>",
  separator = separator || "\n";
  foreach( var i in this ) { 
    if( this.hasOwnProperty( i ) ){ 

        arr[arr.length] = template.replace("<%name%>",i).replace("<%value%>" , this[i]);
    }

  } 
  return arr.join(separator);
};


// that will be print list of names each property in car :)
console.log( "<ul>" + yourCar.view( "<li><%name%><li>") +"</ul>") ;

這只是一個簡單的例子,您可以以某種方式擴展以達到您的目的。 (某些屬性的getter,例如-圖像屬性,getter 可能會立即返回圖像標簽:))

我沒有測試過這個,可能缺少逗號或其他東西。

享受!

一個比任何這些都簡單得多的解決方案只是做這樣的事情:

for(const [key, value] of Object.entries(car)) {
     //code, key being the property name, and value being the value of said key
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM