javascript - 将值推送到数组,并从数组中打印值
问题描述
我正在尝试制作 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);
}
}
}
解决方案
我不明白你想在这里实现什么:但是关于数组以及如何添加项目和打印它的值,这是实现它的一种方法:
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]);
}
推荐阅读
- c# - Quartz.net 在删除作业时抛出 JobPersistenceException
- python - ModuleNotFoundError:没有名为 packageA.innterPackageA 的模块
- javascript - 如何根据类名获取Id的元素
- javascript - 如何在 React Native 中为 svg 文件的一部分设置动画
- c++ - 来自 iostream 或内存缓冲区的 Apache Arrow 表
- scala - 从 spark/scala 中的 s3 读取时,分区 id 被隐式转换
- nuget - TeamCity上的Nuget还原忽略版本?
- javascript - 在 jQuery 中访问动态变量
- pip - pipenv-2018.11.26 虽然确实存在,但由于 setuptools 无法使用 pip 安装
- javascript - React Js SetState 不起作用,应该在我的代码中做些什么来修复它