我正在使用 Canvas 2d 上下文将文本写入屏幕..
为了实现此目的,我让它运行我创建的文本对象数组,现在我拥有具有 3 个属性的文本对象:
text.text
text.x
text.y
text.text 保存要写入的字符串,text.x 保存 x 位置的值,text.y 保存 y 位置的值
我是否可以跳过 text.text 属性?
例如,现在看起来像这样:
var textStrings = [];
textStrings[0] = {};
textStrings[0].text = "hello";
textStrings[0].x = 0;
textStrings[0].y = 10;
textStrings[1] = {};
textStrings[1].text = "world";
textStrings[1].x = 10;
textStrings[1].y = 10;
但是有什么办法可以让我做这样的事情:
textStrings = [];
textStrings[0] = {};
textStrings[0] = "hello";
textStrings[0].x = "0";
textStrings[0].y = 10;
textStrings[1] = {};
textStrings[1] = "world";
textStrings[1].x = 10;
textStrings[1].y = 10;
基本上是对象或其他东西的默认属性...
现在只要我做类似的事情
textStrings[0] = "hello";
它将 textStrings 更改为字符串而不是对象,然后我无法再向它添加属性,因为它是原始数据类型。
谢谢
最佳答案
您可以使用 String 对象代替原始值:
var a = new String("hello");
a.x = "0";
a.y = 10;
var b = new String("world");
b.x = "10";
b.y = 10;
var textStrings = [a, b];
您还可以使用特殊对象。当要将对象转换为字符串时,会自动使用 toString
方法:
function Text(t, x, y) {
this.text = t; this.x = x; this.y = y;
}
Text.prototype.toString = function() { return this.text; }
alert(new Text("hello", 0, 0)); // implicit string conversion
console.log(""+new Text("world", 10, 10)); // explicit string conversion
我猜你无论如何都会有这样的构造函数,以简化 textStrings
数组的语法。
关于javascript - 对象的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10825513/