簡體   English   中英

將值推送到數組,並從數組打印值

[英]Push values to array, and print values from array

我正在嘗試制作 js 類,我將在其中執行以下操作。 發送帶有用法(編號)的汽車名稱(txt)。 對於兩種汽車,我有一些計算,然后我需要將這些值存儲在數組中。 在我存儲在數組中后,我需要再次執行並存儲在同一個數組中。 完成后,我需要使用用法說明從數組中打印數據。 我不知道我的邏輯是否正常,因為我正在開始學習 JS 一些建議或課堂解決方案對我來說很多。

<body>
    <input type="text" id="name">
    <input type="text" id="vrijednost">
    <button type="button" onclick="submit()">Submit</button>
    <p id="demo"><p>
</body>
<script src="cons.js"></script>
<script>
    function submit(){
        name = document.getElementById('name').value;
        vrijednost = document.getElementById('vrijednost').value;

        test = new CarUsage(name, vrijednost)
        console.log(test.get());

    } 
</script>

class CarUsage{

    constructor(total, car){}

    calCarUsage(name, usage){

        let car = {     
            carName: name,   
            carUsage: usage    
        };

        if(car.carName=='Mercedes'){
            this.car = "Mercedes";          
            this.total = 20 + usage * 10;  
            return store(this.car, this.total) 
        }

        else if(car.carName==='Golf'){ 
            this.car = "Golf";
            this.total = 800; 
            return store(this.car, this.total)
        }           
        else{
            this.car === "Other";
            this.total === '160' ;

            return store(this.car, this.total)

        }

    }

    store(name, usage){ 
        var usages = {carName:name, usage:usage};  
    }

    get(){
        for(i=0;i<usages.length;i++){
            alert("Car:- "  + usages[i].carName + "Usage:- "  + usages[i].usage);
        }
    }

 } 

我不明白你想在這里實現什么:但是關於數組以及如何添加項目和打印其值,這是實現它的一種方法:

 var sentence = []
    var words = ['this', 'is', 'one', 'way', 'of', 'push', 'to', 'an', 'array','and','print', 'the', 'values']
    for(var i = 0; i < words.length; i++){
     sentence.push(words[i]);
    }
    console.log("Here's my sentence: " + sentence.join()) // => Here's my sentence: this is one way of pushing to an array and print the values

或者如果您只是想打印數組中的每個項目:

for(var i = 0; i < sentence.length; i++){
 console.log(sentence[i]);
}

暫無
暫無

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

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