gpt4 book ai didi

javascript - 无法访问 coffeescript 中的属性

转载 作者:行者123 更新时间:2023-11-30 18:37:20 25 4
gpt4 key购买 nike

我打算得到“0,0,0,0”但只得到“,,,”。看来我在 coffeescript 中访问类属性的方式无法正常工作。

class Tetris
@array: []

constructor: (@width, @height) ->
@array = new Array(@width*@height)
@array.map (item, i) -> this[i]=0

to_s: ->
array_item for array_item in this.array

$ ->
t = new Tetris 2,2
alert t.to_s()

编译后的javascript如下:

(function() {
var Tetris;
Tetris = (function() {
Tetris.array = [];
function Tetris(width, height) {
this.width = width;
this.height = height;
this.array = new Array(this.width * this.height);
this.array.map(function(item, i) {
return this[i] = 0;
});
}
Tetris.prototype.to_s = function() {
var array_item, _i, _len, _ref, _results;
_ref = this.array;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
array_item = _ref[_i];
_results.push(array_item);
}
return _results;
};
return Tetris;
})();
$(function() {
var t;
t = new Tetris(2, 2);
return alert(t.to_s());
});
}).call(this);

最佳答案

试试这个

class Tetris
constructor: (@width, @height) ->
@array = for x in [ 0 ... (@height*@width)] then 0
console.log @array
to_s: ->
array_item for array_item in this.array

$ ->
t = new Tetris 2, 2
alert t.to_s()

或者这个

class Tetris
constructor: (@width, @height) ->
@array = (0 for x in [0...(@height*@width)])
console.log @array
to_s: ->
array_item for array_item in this.array

$ ->
t = new Tetris 2, 2
alert t.to_s()

它们都生成相同的 javascript

这是涵盖列表理解的部分。 http://jashkenas.github.com/coffee-script/#loops

关于javascript - 无法访问 coffeescript 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7870327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com