【发布时间】:2017-09-30 17:56:54
【问题描述】:
我进行了一些搜索,但我总是找到如何访问数组对象的值,或者类似的东西。
我想要实现的是将值从数组传递到我的对象属性值。
让我展示我的实际代码以便更好地理解。
//the array i want to use in my object
var grades = [3, 7, 6, 16, 8, 2, 12, 5, 19, 12, 8, 2, 15, 12, 17, 16, 4, 19, 9, 11, 18, 1, 15, 19, 8]
//My rectangle prototype. Some values are changed using the createRectangle() function.
var rectangle = {
x: Parameters[2], // this is the center of the rectangle
y: 0,
dx: 0, // delta x and y are the movement per frame
dy: 0,
w: 70, // size
h: 55,
color: "yellow",
text: null,
textColor: "black",
cutX: Parameters[2], //X position of cut mark (same as rectangle)
cutY: 700,
dxCut: 0,
dyCut: 0,
cutWidth: 75,
cutHeight: 30,
cutColor: "#ffffcc",
cutStroke: "purple",
strokeHeight: 5,
draw() { // function to draw this rectangle
ctx.fillStyle = this.color;
ctx.fillRect(this.x - this.w / 2, this.y - this.h / 2, this.w, this.h);
ctx.fillStyle = this.textColor;
ctx.fillText(this.text, this.x, this.y);
ctx.fillStyle = this.cutColor;
ctx.fillRect(this.cutX - this.cutWidth / 2, this.cutY - this.cutHeight / 2, this.cutWidth, this.cutHeight);
ctx.fillStyle = this.cutStroke;
ctx.fillRect(this.cutX - this.cutWidth / 2, this.cutY - 8 / 2, this.cutWidth, this.strokeHeight);
},
update() { // moves the rectangle
this.x += this.dx; //x = x + dx (do we need to update the position ? )
this.y += this.dy;
this.cutX += this.dxCut;
this.cutY += this.dyCut;
}
};
//function to create rectangle object
function createRectangle(settings) {
return Object.assign({}, rectangle, settings);
}
// function to store rectangles in object array and then spawn rectangle
function spawnRectangle() {
if (spawnCountdown) {
spawnCountdown -= 1;
} else {
rectangles.push(
createRectangle({
y: canvas.height / 1.5,
text: function findGrade() {
for (var i=0; i<grades.length; i++) {
return this.grades[i];
}
},
dx: 2,
dxCut: 2,
cutY: randPosition(),
})
);
spawnCountdown = spawnRate;
}
}
所以,如果我稍微解释一下,在我的整个代码中,我有一个函数可以遍历一个数组以查看要创建多少个矩形。然后,每次使用函数spawnRectangle() 创建一个矩形并将这个矩形推送到一个对象数组。
我想要做的是从spawnRectangle() 函数创建的每个矩形都有来自我的gradesarray 的自己的文本属性值。
请注意,我在这里打印了我的 grades 数组,但在实际代码中,该数组是从服务器端代码生成的(所有这些值都由 ajax 更新)。
【问题讨论】:
-
它有没有用过?
rectangle或settings是什么? -
for函数中的for循环是无用的,因为它从第一次迭代中返回(稍后代码中的另一个for循环也是如此)。 -
为什么
return来自for循环? -
@NinaScholz 是的,它有效,但首先打印出我的整个数组,然后只打印出索引 0。我刚刚用关于
rectangle的部分代码编辑了我的问题。而settings是来自createRectangle函数的参数。这实际上是我在rectangles.push(createRectangle({ });内部传递的属性值 -
@ibrahimmahrir 好的,那么实现我想要的最简单的方法是什么?目前,我只是尝试在迭代或创建新的矩形对象但使用下一个数组索引值时将我的
grades数组值传递给rectangle。
标签: javascript arrays object for-loop properties