javascript - 将数组传递给 TypeScript 中的构造函数

标签 javascript typescript

我开始在 TypeScript 中构建一个放置游戏(比如 cookie clicker - 但更糟糕!)。我是 TypeScript 的新手,主要是 JavaScript。

当我将“成本”从数字更改为键入“成本”时,问题出现了。成本背后的想法是一些后来的物体(如有翼老鼠)会消耗多种资源,而不仅仅是报废。我怀疑我的 Cost 实现在某处出错了,或者构造函数没有正确构建。或者它没有正确实例化。

目前,当检查“resourceList["rat"].cost.costList["scrap"]"时,返回未定义。这会导致“老鼠”按钮永远处于禁用状态。

class Resource {
    name: string;
    amount : number;
    cost: Cost;
    value: number;
    display() : string
    {
        if(this.amount - Math.floor(this.amount) > 0)
        {
            return this.amount.toFixed(2);
        }
        else
            return this.amount.toString();
    }
}

class Cost {
    costList: { [id: string] : number; } = {};
    constructor(res:string[], cost:number[]){
        var i = 0;
        for(var r in res)
        {
            var c = cost[i];
            this.costList[r] = c;
            i++;
        }
        return this;
    }
}

class Scrap extends Resource {
    constructor(public amount) {
        super();
        this.name = "scrap";
        this.cost = new Cost([""],[0]);
        document.getElementById('scrapLbl').innerHTML = this.name + ": ";
    }
}

class Rat extends Resource {
    constructor(public amount) {
        super();
        this.name = "rat";
        this.cost = new Cost(["scrap"],[10]);
        this.value = 1;
        document.getElementById('ratLbl').innerHTML = this.name + ": ";
    }
}

class wRat extends Resource {
    constructor(public amount) {
        super();
        this.name = "wrat";
        this.cost = new Cost(["scrap", "rat"],[10, 1]);
        this.value = 1;
        document.getElementById('wratLbl').innerHTML = this.name + ": ";
    }
}

var resourceList: { [id: string] : Resource; } = {};
var curScrap = new Scrap(0);
var curRat = new Rat(0);
var curWRat = new wRat(0);
resourceList["scrap"] = curScrap;
resourceList["rat"] = curRat;
resourceList["wrat"] = curWRat;

function updateView()
{
    document.getElementById('scrapId').innerHTML = resourceList["scrap"].display();
    document.getElementById('ratId').innerHTML = resourceList["rat"].display();
    if(resourceList["scrap"].amount >= resourceList["rat"].cost.costList["scrap"])
    {
        document.getElementById('scrapRat').disabled = false;
    }
    else
    {
        document.getElementById('scrapRat').disabled = true;
    }
    document.getElementById('ratId').title = resourceList["rat"].cost.toString();
}

function updateValues()
{
    if(resourceList["rat"].amount > 0)
        resourceList["scrap"].amount += (resourceList["rat"].value * resourceList["rat"].amount)/10;
}

function collectScrap()
{
    resourceList["scrap"].amount += 1;
}

function scrapRat()
{
    //cost
    resourceList["scrap"].amount -= resourceList["rat"].cost.costList["scrap"];
    //create
    resourceList["rat"].amount += 1;
    //update cost
    resourceList["rat"].cost.costList["scrap"] *= 1.12;
}

window.setInterval(function(){
    this.updateValues();
    updateView();
}, 100);

不确定您是否需要 HTML,但这里是:

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Scrap Clicker</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <script src="js/jquery-2.2.1.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</head>
<body>

<label id="scrapLbl" ></label> <span id="scrapId">0</span>
<label id="ratLbl" ></label> <span id="ratId">0</span>
<label id="wratLbl" ></label> <span id="wratId">0</span>
<div>
    <button title="Free" data-toggle="popover" data-trigger="hover" data-content="Dig!" class="btn btn-lg btn-primary" onclick="collectScrap()">collect scrap</button>
    <button title="10 Scrap" data-toggle="popover" data-trigger="hover" data-content="Strap some scrap to a rat, now you've got a Scrap-Rat!" class="btn btn-lg btn-primary" onclick="scrapRat()" id="scrapRat" disabled>scrap rat</button>
    <button title="10 Scrap, 1 rat" data-toggle="popover" data-trigger="hover" data-content="Strap some scrap to a Scrap-Rat, now you've got a Flying-Scrap-Rat!" class="btn btn-lg btn-primary" onclick="wRat()" id="wRat" disabled>Winged scrap rat</button>

</div>
<script src="game.js"></script>
<script>
    $(document).ready(function(){
        $('[data-toggle="popover"]').popover();
    });
</script>
</body>
</html>

奖励积分:向我展示一种更好的方式来跟踪资源和成本!

最佳答案

您的问题不在 typescript 中,而是在您的 for..in 循环中:

let myArray = ["a", "b", "c"]
for (var item in myArray) {
    console.log(item);
}
// 0,1,2

在数组上使用 for...in 循环时,“item”实际上是“index”。您希望您的 Cost 类是:

class Cost {
    costList: { [id: string] : number; } = {};
    constructor(res:string[], cost:number[]){

        for (let i = 0; i < res.length; i++) {
            this.costList[res[i]] = cost[i];
        }
    }
}

编辑:关于您的奖励积分,实现Cost 的更 typescript 方式是使用接口(interface):

interface Cost {
    [key: string]: number;
}

class Resource {
    cost: Cost;
    //...
}

class Rat extends Resource {
    constructor(public amount) {
        super();
        this.cost = <Cost>{
            "scrap": 0
        };
    }
}

关于javascript - 将数组传递给 TypeScript 中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35949108/

相关文章:

javascript - Lodash 拆分对象

javascript - 从禁用的复选框中发布值

javascript - HTML5/Javascript 以一定 Angular 在屏幕上移动对象

angular - 如何从 Observable 中定位和删除主题?

javascript - typescript 对象奇怪的类型语法

javascript - Angular 5 错误 :Can't bind to 'ngForFor' since it isn't a known property of 'li'

javascript - js jquery 转发保存的事件

javascript - 当总计为 0 时隐藏 <li>

css - Angular2 获取窗口宽度 onResize

node.js - 开 Jest - 语法错误 : Cannot use import statement outside a module with @nestjs/axios