本文介绍了完全控制很多对象的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在开发一款javascript游戏,它会产生并终止形状。因此,我需要完全控制这些正在产生的形状。我想做以下事情,但我不知道如何做到这一点: 我想定义一个构造函数 Shape 。 然后,我想创建一个函数,当它被调用时,它适用于所有 Shape 存在并且能够更改每个属性。 (例如,我调用函数 moveAll(),并将所有形状的 this.y 增加1。) 我也希望能够用一个函数终止一个特定的 Shape ,或者添加一个 Shape 带一个函数。 我的主要问题是: var x = new Shape(); var y = new Shape(); ... 我不想制作一百万个变量。我需要一种能够立即制作大量形状的方法,并且仍然可以单独控制每一种形状。如果我创建了一个数组,我将如何单独控制每件事? 任何事情都有帮助,我只需要理解构造函数概念的基础。 解决方案您可以制作一组形状: let shapes = [] //这将创建6个形状 for(let i of [0,1,2,3,4 ,5]){ shapes.push(new Shape())} 如果一个形状有一个 id ,您可以终止它。 //增加id计数器让id = 0 // x和y是可选的起始位置函数Shape(x,y){ this.id = id ++ this.y = y || 0 this.x = x || 0 } //从数组中删除形状函数terminate(id){$ b $ shapes = shapes.filter(shape => shape.id! == b)} //或者添加一个形状函数spawn(){ shapes.push(new Shape())} 现在您已经拥有了自己的形状。 移动所有形状的最简单的方法是这样的: function moveAll(){ shapes.forEach shape => shape.y ++)} 运行时间会随着数字 $ b 更新 moveAll ,每个请求 function moveAll(){ shapes.forEach(shape => { if(shape.type === true){ shape。 y ++ } else { shape.y-- } })} I am working on a game in javascript that spawns and terminates shapes. Therefore, I need full control over these shapes that are being spawned. I want to do the following, but I am not sure on how to do it:I want to define a constructor Shape.Then, I want to make a function so that when it is called, it applies to ALL of the Shape in existence and being able to change each ones attribute. (For example, I call function moveAll() and all of the shapes' this.y increments by one.)I also want to be able to terminate a specific Shape with a function, or add a Shape with a function.My main problem is this:var x = new Shape();var y = new Shape();...I don't want to make a million variables. I need a way to make tons of shapes at once and still be able to control each one individually. And if I made an array, how would I control everything individually?Anything helps, I just need a basis to understand the concept of constructors. Thanks in advance! 解决方案 You could make an array of shapes:let shapes = []// this will create 6 shapesfor(let i of [0,1,2,3,4,5]) { shapes.push(new Shape())}If a shape has an id you can terminate it:// incrementing id counterlet id = 0// x and y are optional starting positionsfunction Shape(x, y) { this.id = id++ this.y = y || 0 this.x = x || 0}// remove the shape from the arrayfunction terminate(id) { shapes = shapes.filter(shape => shape.id !== id)}// or add a shapefunction spawn() { shapes.push(new Shape())}Now you have your shapes.The simplest way to move all shapes would be something like this:function moveAll() { shapes.forEach(shape => shape.y++)}Runtime for this will increase as the number of shapes increase.updated moveAll, per requestfunction moveAll() { shapes.forEach(shape => { if(shape.type === true) { shape.y++ } else { shape.y-- } })} 这篇关于完全控制很多对象的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 06:27