Titanium textField存储为整数

时间:2015-10-28 10:40:59

标签: javascript titanium textfield appcelerator

我正在尝试将引用存储到数组中的多个文本字段中。当我尝试访问数组的元素时,我得到一些整数而不是文本字段对象!我无法弄清楚为什么会发生这种情况......

var textfields = [];
function doClick(e) {        
    var txtField = Ti.UI.createTextField({
        value:"test"
    });
    textfields.push(txtField);
    $.index.add(txtField);

    for(var textfield in textfields) {
        console.log("stored value : "+textfield);
    }
}

$.index.open();

三次“点击”后的输出:

[INFO] :   ---click---
[INFO] :   stored value : 0
[INFO] :   ---click---
[INFO] :   stored value : 0
[INFO] :   stored value : 1
[INFO] :   ---click---
[INFO] :   stored value : 0
[INFO] :   stored value : 1
[INFO] :   stored value : 2

但是当我对整个数组进行字符串化时,我看到textField IS在里面,但我不知道如何访问它。 这是包含两个textFields的数组:

[
   {
      "enabled":true,
      "selection":{
         "length":0,
         "location":0
      },
      "backgroundRepeat":false,
      "children":[

      ],
      "rect":{
         "height":45,
         "y":61,
         "x":137,
         "width":47
      },
      "value":"voilà",
      "visible":true,
      "size":{
         "height":45,
         "y":0,
         "width":47,
         "x":0
      },
      "keepScreenOn":false,
      "apiName":"Ti.UI.TextField",
      "maxLength":-1,
      "bubbleParent":true
   },
   {
      "enabled":true,
      "selection":{
         "length":0,
         "location":0
      },
      "backgroundRepeat":false,
      "children":[

      ],
      "rect":{
         "height":45,
         "y":107,
         "x":137,
         "width":47
      },
      "value":"voilà",
      "visible":true,
      "size":{
         "height":45,
         "y":0,
         "width":47,
         "x":0
      },
      "keepScreenOn":false,
      "apiName":"Ti.UI.TextField",
      "maxLength":-1,
      "bubbleParent":true
   }
]

根据我的理解,textfield.value应该可以工作,但它会返回“undefined”,因为textfield本身就是一个数字......如何访问我存储在数组中的元素?

2 个答案:

答案 0 :(得分:4)

你的for...in错了......应该是:

for(var textfield in textfields) {
    console.log("textfield : "+textfields[textfield]);
    console.log("textfield : "+textfields[textfield].value);
}

for in设置key中的textfield,而不是元素。

请查看此处的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in

在Titanium中循环(使用Alloy时)的更好方法是underscore

_.each(textfields, function(textfield){
    console.log('textfield value:' + textfield.value);
}

答案 1 :(得分:2)

请尝试forEach而不是for-in循环。见下面的代码。

textfields.forEach(function(textField){
    console.log(textField.value);
});