Titanium text字段存储为整数

Titanium textField stored as integer

本文关键字:整数 存储 字段 text Titanium      更新时间:2023-09-26

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

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,但我不知道如何访问它。这是一个数组,里面有两个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应该有效,但它返回"未定义",因为textfield本身是一个数字…我如何访问我存储在数组中的元素?

您的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

在钛中循环的更好方法(当使用合金时)是underscore

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

请在循环中尝试forEach。请参阅以下代码。

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