无法访问在For循环(Javascript)之外声明的变量

问题描述 投票:0回答:1

我只是无法访问在Javascript中的For循环外声明的变量。 For循环位于一个object属性中,该属性位于Function内部,它用于使用Chart.Js绘制图表。

它有什么解决方法吗?

Here comes the code:

function chart1Update() {

var string = "['text1', 'text2', 'text3', 'text4']"

// bar chart data

var barData = {
labels : [
{% for item in string %} // <==== THE PROBLEM IS RIGHT HERE (string) <====
"{{ item }}",
{% endfor %}
],
datasets : [{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
data : [
{% for item in ['1499', '1554', '1661', '1658'] %}
"{{ item }}",
{% endfor %}
]
}
]
}
javascript jquery arrays json chart.js
1个回答
0
投票

{% for item in string %}看起来不像javascript。是一些红宝石的东西或东西?它正在寻找变量string,它定义在标记来自的任何非javascript语言中,并且由于它无法访问任何javscript变量而未定义或未初始化。

如果你把它变成JS数组(而不是像当前那样在字符串里面的数组声明),你可以直接分配js数组而不用循环,即

var string = ['text1', 'text2', 'text3', 'text4']; //no double quotes on the outside
var barData = {
labels : string,
//...

你的data循环工作的原因是因为变量(数组文字)是在标记内部定义的,因此它可以访问它。

© www.soinside.com 2019 - 2024. All rights reserved.