我是TypeScript的新手,而且我坚持使用JSON.我需要创建一个简单的JSON对象,但我仍然没有这样做.这是我的第一次尝试:
output: JSON; //declaration
this.output = {
"col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"},
"col2":{"Attribute1": "value4", "Attribute2": "value5", "Attribute3": "value6"},
"col3":{"Attribute1": "value7", "Attribute2": "value8", "Attribute3": "value9"}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用.我想我应该使用JSON.stringify函数.这是我的尝试:
obj: any; //new object declaration
this.obj = {
"col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"},
"col2":{"Attribute1": "value4", "Attribute2": "value5", "Attribute3": "value6"},
"col3":{"Attribute1": "value7", "Attribute2": "value8", "Attribute3": "value9"}
}
this.output.stringify(this.obj);
Run Code Online (Sandbox Code Playgroud)
但是这仍然会调用TypeError.总结一下我的问题:如何在TypeScript中正确创建和初始化JSON对象?
让我们演示一个简单的HTML代码示例,如下所示:
<div data-icon="\25B6">Title</div>
Run Code Online (Sandbox Code Playgroud)
我希望这个元素有一个由它的数据属性(data-icon)设置的前缀图标,所以我设置了这样的CSS文件:
div:before {
content: attr(data-icon);
}
Run Code Online (Sandbox Code Playgroud)
我希望这个例子的输出看起来像这样:
?Title
Run Code Online (Sandbox Code Playgroud)
所有我能得到的不是所需的输出,而是:
\25B6Title
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:我做错了什么/我错过了什么?
JSFiddle示例:http://jsfiddle.net/Lqgr9zv6/
快速提问 - 如何访问"以上两级"属性?TypeScript中的测试示例:
export class Test {
testVariable: string;
constructor() { }
TestFunction() {
MyFunctions.Proxy.Join() { //some made up function from other module
//HERE
//How can I here access testVariable property of Test class?
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者甚至可以在TypeScript(或一般的JavaScript)中访问这样的属性?
编辑+回答:由于我的问题不够明确,我带来了一些关于这个问题的新信息.通过启动程序员这是一个非常常见的问题.
这里的问题是this改变它的上下文 - 首先它指的是类Test,然后它指的是我的内部函数 - Join().为了实现正确性,我们必须使用lambda表达式进行内部函数调用或使用一些替换值this.
第一个解决方案是接受的答案.
其次是:
export class Test {
testVariable: string;
constructor() { }
TestFunction() {
var myClassTest: Test = this;
MyFunctions.Proxy.Join() { //some made up function from other module
myClassTest.testVariable; //approaching my …Run Code Online (Sandbox Code Playgroud)