如何从搜索框中的特定字母开始获取单词

时间:2015-03-11 06:57:40

标签: javascript titanium-alloy

   var items = ['Television', 'Music System', 'Car', 'Bus','Train',
 'Computer', 'Lap Top', 'I-Phone', 'Tablet', 'Electronics', 'Watch','Mouse']   

   function fillData() {
   var data = [];
    for (var i = 0; i < items.length; i++) {
    var row = Ti.UI.createTableViewRow({
        height : 50,
        title : items[i],
        color : 'pink',
        hasChild : true,
        font : {
            fontSize : 14
        },
    });
    data.push(row);
      }
       $.table.setData(data);
      }
      fillData();
     $.tabGroup.open();

当我输入特定字母时,它会以任何顺序显示包含该字母的所有单词.... 但是我只想从那个特定的字母开始那些话......

1 个答案:

答案 0 :(得分:0)

在这里,你有一个方法被添加到数组原型中,用于搜索关键字的单词外观。

//Define Array SearchFor Word
//  ussage for entire word search: array.searchForWords('KeyWord');
//  ussage for word begining search: array.searchForWords('KeyWord', true);
Array.prototype.searchForWords = function(Word, startingwith)
{
    if (Word == undefined || Word.length == 0) return this;
    if (this.lenght == 0) return "";
    var result = [];
    Word = Word.toLowerCase();

    for (var i = 0; i < this.length; i++)
    {
        var thisWord = this[i].toLowerCase();
        if (thisWord.indexOf(Word) != -1)
        {
            if (!!startingwith)
            {
                if (thisWord.split(Word)[0].length == 0)
                {
                    result.push(this[i]);
                }
            }
            else
            {
                result.push(this[i]);
            }
        }
    }
    return result.sort();    
}

 var items = ['Television', 'Music System', 'Car', 'Bus','Train',
 'Computer', 'Lap Top', 'I-Phone', 'Tablet', 'Electronics', 'Watch','Mouse']   

alert('search for "le" :' + items.searchForWords("le"));
alert('search for "ar" :' + items.searchForWords("ar"));
alert('search for "t" :' + items.searchForWords("t"));
// Search only for words starting with "t" t=T and T=t
alert('search for "t" :' + items.searchForWords("t", true));