Titanium textField 存储为整数

Titanium textField stored as integer

我正在尝试将对多个文本字段的引用存储在一个数组中。当我尝试访问数组的元素时,我得到了一些整数而不是文本字段对象!我不明白为什么会这样……

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();

三个 "clicks" 后的输出:

[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,但我不知道如何访问它。 这是里面有两个文本字段的数组:

[
   {
      "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 应该可以,但它 returns "undefined" 因为文本字段本身是一个数字......我如何访问我存储在数组中的元素?

请尝试使用 forEach 而不是 for-in 循环。请参阅下面的代码。

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

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

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

for intextfield 中设置 key,而不是元素。

查看此处的文档: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);
}