Search code examples
javascriptmobiletitaniumstring-length

Measuring the length of an array, not characters in JavaScript


I have one problem regarding the length function. The problem is that when more than one entries come in the variable, it calculates the length perfectly but for a single entry, it starts to measure the number of characters instead of the amount of elements in the array. I want the alert to show 1 because there is one entry: finance consultant, but it's showing 18.

var win = Titanium.UI.createWindow({ backgroundColor:'#FFF' });
var tableView1=Titanium.UI.createTableView(); 
var Row = [];
Titanium.Yahoo.yql(
  'select * from html where url="http://..." '
  + 'and xpath="//tbody/tr/td/a/font" limit 25', 
  function(e) {
    results = e.data.font;
    results = results.content;
    alert(results.length);
    for (var i = 0; i < results.length; i++) {
      var rss = results[i];
      var rssRow = Titanium.UI.createTableViewRow({ ... });
      var titleLabel = Titanium.UI.createLabel({ ... });
      rssRow.add(titleLabel);
      Row.push(rssRow);
    };

    tableView1.setData(Row);
  });

win.add(tableView1);
win.open();

Solution

  • You can try the following.

    results = results.content;
    if (typeof results === 'string')
      results = [results];
    alert(results.length);
    

    So now you've forced a result that is a string to be an array of one string. The rest of your code should work unmodified.