我正在尝试在js类中进行后续操作。发送带有用法(编号)的汽车名称(txt)。对于两种汽车,我需要进行一些计算,然后将这些值存储在数组中。 将其存储在阵列中后,我需要再次执行并将其存储在同一阵列中。 一旦完成,我需要使用用法desc将数据打印出数组。 我不知道我的逻辑是否还可以,因为我开始学习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);
}
}
}
答案 0 :(得分:0)
我不明白您在这里想要达到的目标: 但是关于数组以及如何添加项目和打印其值,这是实现它的一种方法:
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]);
}