我需要制作一个脚本,但我不知道如何完成它。 这就是我要做的事情:
(1)写一个类盒子。这个类有一个默认的构造函数和一个名为boxes的空数组。
进一步有这个3类方法:
1)插入add方法将Box放入box-array。 2)插入方法大小以获得数组的实际大小。 3)插入toString方法,在一个字符串中返回颜色和音量。
(2)继续执行init函数:
2.3绕数组对象中的每个对象转一圈,将其添加到数组框
2.4创建一个toString方法,在一个HTML P-tag中返回数组中的每个对象。
我希望这对你们有意义,如果有人可以帮助我,那将是一个很大的帮助!
提前非常感谢!
更新:我已经将代码编辑为现在的代码。
window.addEventListener("load", init, false);
function init() {
// (2.1)
let object1 = new Box(20, 8, 3, "white");
let object2 = new Box(30, 20, 10, "Brown");
let object3 = new Box(50, 40, 20);
// (2.2)
let boxes = new Boxes();
// (2.3)
boxes.push(object1);
boxes.push(object2);
boxes.push(object3);
// 2.4
var str=""
for (let i = 0 ; i < boxes.size() ; i++){
str += "<p>"+boxes.toString(i)+"<p>"
}
}
class Box {
constructor(length, width, height, color = "blue") {
this.length = length;
this.width = width;
this.heigt = height;
this.color = color;
}
volume() {
return this.length * this.width * this.height;
}
toString() { // String templates
return `Volume: ${this.volume()} --- Kleur: ${this.color}`;
}
}
// (1) class Boxes
class Boxes {
constructor(){
this.boxes = [];
}
add(Box){
this.boxes.push(Box);
}
size(){
return this.boxes.length;
}
toString(i){
this.boxes[i].toString();
}
}
答案 0 :(得分:0)
我不太明白3)这意味着所以我会假设你想要给出索引的盒子颜色和体积(如果我错了,请纠正我)
class Boxes{
//init property called boxes to an empty array when creating Boxes object
constructor(){
this.boxes = [];
}
//return the length of the boxes
size(){
return this.boxes.length;
}
//add a box by pushing it to the array
add(box){
this.boxes.push(box);
}
//print the volume and color of a box given the index
toString(i){
this.boxes[i].toString();
}
}
代表2:
//2.3
//do you have to push the objects to object?
//use this if you don't have to
boxes.push(object1);
boxes.push(object2);
boxes.push(object3);
//use this if you pushed your objects into an array called object
objects.forEach(function(singleObject){
boxes.push(singleObject);
});
//2.4
//Iterate every object in boxes and print out their volume and color
//Do you have to create a P tag or just wrapped the string with <p></p>?
//This answer assumes that you just wrap it with <p></p>. Correct me if I'm wrong
var str = "";
//option 1 Using foreach loop
boxes.boxes.forEach((singleBox){
str += "<p>"+singleBox.toString()+"</p>";
});
//option 2 Using for loop
for(var i = 0; i < boxes.size(); i++){
str += "<p>"+boxes.toString(i)+"</p>";
}
//now str contains every object's color and volume wrapped in P tag