【问题标题】:Why won't this javascript run? [closed]为什么这个 javascript 不能运行? [关闭]
【发布时间】:2012-11-20 19:20:39
【问题描述】:

这里我有两个“类”制作卡片和卡片。 Cards 本质上是一个具有特定方法的数组:

  • 添加卡片
  • 移除卡
  • 排序和随机播放

Card 是一个对象,用于保存花色值并输出连接两者的字符串。

我的问题是尝试在单击按钮时运行此代码,即setup()。 我发现当我刚刚创建一张卡片时,它仍然可以运行。我知道这一点是因为输出仍然会变为 hello world。

但是当我尝试将卡片添加到卡片类或卡片组时。脚本停止运行。我不知道这是为什么,我感觉它不喜欢我使用数组的方式。

这是第一个问题。

我的第二个问题是当我

var temp= new card('c','2');
alert(temp.getvalue());

这也失败了。

任何关于我在这里做错了什么的见解都会有所帮助并受到赞赏。

function setup() {
    var temp = new card('c', '2');
    var textbox = document.getElementById("output");
    textbox.value = "Hello, world!";
};

Array.prototype.shuffle = function () {
    for (var i = this.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var tmp = this[i];
        this[i] = this[j];
        this[j] = tmp;
    }

    return this;
}

function card(s, v) {
    this.suit = s;
    this.value = v;

    this.getvalue = function () {
        return (suit.toString() + value.toString());
    };

    this.getSortOrder = function () {
        var factor;
        if (this.suit == 'c') {
            factor = 0;
        }
        else if (this.suit == 'd') {
            factor = 1;
        }
        else if (this.suit == 'h') {
            factor = 2;
        }
        else if (this.suit == 's') {
            factor = 3;
        }
        else {
            factor = -2;
        }

        return (this.value + 13 * factor);
    };
};

function Cards() {
    this.list = new Array();

    this.Addcard = function (c) {
        list.push(c);
    };

    this.removeCard = function (c) {
        list.splice(list.indexOf(c), 1);
    };

    this.lookat = function (i) {
        return list[i];
    };

    this.sort = function () {
        list.sort();
    };

    this.shuffle = function () {
        list.shuffle();
    };

    this.prototype;
};

【问题讨论】:

  • javascript 开发控制台是否出现错误?
  • 每个问题一个问题。
  • Stackoverlow 用户不是调试器。
  • 请考虑发布不是阅读繁琐的代码 - 删除 cmets,正确缩进,将行合并。这样,人们可能会更倾向于帮助您找到解决方案。 =)
  • 我同意@J.Steen 的观点,我花了一分钟来解析代码,然后才发现出了什么问题。删除无用的换行符也会有所帮助,特别是因为 SO 上的代码窗口非常小。

标签: javascript arrays html function object


【解决方案1】:

这是一件事:

this.getvalue = function () {

    return (suit.toString() + value.toString());

};

你需要用这个来获得花色和价值:

this.getvalue = function () {

    return (this.suit.toString() + this.value.toString());

};

编辑:

在您的代码中还有很多类似的内容(请参阅Cards 函数)。 Javascript 不会像其他语言那样自动为您放置“this”,因为它没有类,它有原型。

每当您尝试访问“成员变量”时,给它一些上下文,使用this

其他代码风格提示:

  • 使用 [] 代替 new Array()
  • /**/注释大块代码
  • 构造函数应该大写(Card,不是 Card),函数应该是驼峰式(addCard,不是 Addcard)

【讨论】:

  • 谢谢,有道理,我最初没有这样做是因为我不知道 this 是指指定类中的新函数,还是 this 指的是指定类.
  • 经验法则,this 是调用函数时点左侧的任何内容:thing.func(),即func() 中的this。除非使用“绑定”,否则 90% 的情况都是如此。
猜你喜欢
  • 1970-01-01
  • 2013-04-16
  • 2018-11-19
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
相关资源
最近更新 更多