如何更新钛的全局变量?

时间:2011-09-26 08:52:28

标签: arrays global-variables titanium appcelerator-mobile

我在更新我的阵列方面遇到了一些问题,顺便说一句,这个问题是全局的。

这是我的代码:

Ti.App.dinercolor=["#FF5A00","#007EFF","#dccdc0","#C2FF95","#A700FD","#dccdc0","#dccdc0","#5F9EA0","#dccdc0","#dccdc0","#22A000","#DCCDC0","#dccdc0","#FF003C","#dccdc0","#FF003C","#dccdc0","#22A000","#dccdc0","#FFF191"];

这是我的全局数组,我可以从应用程序的任何地方访问它。

当我想更新数组时,问题出现了:

for(var q=0; q<Ti.App.dinercolor.length; q++){Ti.App.dinercolor[q] = '#dccdc0';}    

所以,在完成操作之后,我期待的数组是这样的:

Ti.App.dinercolor=["#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0"];

但不知怎的,我得到了相同的数组,没有更新,

Ti.App.dinercolor=["#FF5A00","#007EFF","#dccdc0","#C2FF95","#A700FD","#dccdc0","#dccdc0","#5F9EA0","#dccdc0","#dccdc0","#22A000","#DCCDC0","#dccdc0","#FF003C","#dccdc0","#FF003C","#dccdc0","#22A000","#dccdc0","#FFF191"];

请帮帮我,我不知道我在这里做错了什么,

谢谢你,

3 个答案:

答案 0 :(得分:3)

您的代码是正确的,但是您不应该扩展Ti对象,因为会发生类似意外的事情。创建自己的对象,它将起作用。

myObj = {};
myObj.dinercolor = [];

等等。

建议您将应用程序保存在单个上下文中,以便能够从任何位置访问该对象。查看the forging titanium视频系列了解最佳做法。

答案 1 :(得分:1)

我同意Jeff的观点,但是如果你想让上述方法工作,你将需要更新整个数组,你不能只更新元素。

因此,将数组读入新变量,更新特定元素,然后再次设置属性

答案 2 :(得分:0)

在App.js中:

Ti.App.my_variable = 0;

在some_other_page.js中:

Ti.App.my_variable = 101;

在yet_another_page.js中:

alert( Ti.App.my_variable );

这会提醒101 !!