2014-01-30 5 views
0

Я немного передохнул от кодирования в течение нескольких месяцев, и теперь я снова пытаюсь вернуться к нему.Как проверить, содержит ли строка значения массива?

Я работаю над пользовательской книгой для игры в facebook, которая будет собирать данные из всех сообщений, связанных с игрой, и использовать эти данные для начала процесса принятия.

Тем не менее, я пытаюсь ввести выбор для пользователей, чтобы выбрать, какие типы бонусов они предпочитают принимать, и им не удается его применить.

Что я хочу сделать, это взять строку заголовков записей и сравнить ее с массивом выбранных параметров (флажков), чтобы узнать, содержит ли заголовок сообщения любые значения из массива.

Это панель настроек, где пользователи могут выбрать, какие сообщения принять:

$("#rightCol").prepend('<div id="bonus_options_panel">' 
         +'<ul id="bonuses"><legend><b>Select Bonuses to accept...</b></legend>' 
         +'<li><label>Hungry No More <input type="checkbox" value="heroic companions!" class="bonus_select_option"></label></li>' 
         +'<li><label>Pikemen <input type="checkbox" value="extra pikes!" class="bonus_select_option"></label></li>' 
         +'<li><label>Swordsmen <input type="checkbox" value="recruited swordsmen!" class="bonus_select_option"></label></li>' 
         +'<li><label>Valuable Treasure <input type="checkbox" value="valuable treasure!" class="bonus_select_option"></label></li>' 
         +'<li><label>Jousting Competition <input type="checkbox" value="jousting game!" class="bonus_select_option"></label></li>' 
         +'<li><label>Gamble <input type="checkbox" value="wants to gamble." class="bonus_select_option"></label></li>' 
         +'<li><label>Extra Lumber <input type="checkbox" value="has extra lumber!" class="bonus_select_option"></label></li>' 
         +'<li><label>Foreign Traders <input type="checkbox" value="attracted foreign traders!" class="bonus_select_option"></label></li>' 
         +'<li><label>Buxom Wenches <input type="checkbox" value="inviting friends over!" class="bonus_select_option"></label></li>' 
         +'<li><label>Plague <input type="checkbox" value="kingdom has the plague!" class="bonus_select_option"></label></li>' 
         +'<li><label>Legendary Bard <input type="checkbox" value="hosting a legendary bard!" class="bonus_select_option"></label></li>' 
         +'<li><label>Wild Horses <input type="checkbox" value="found wild horses!" class="bonus_select_option"></label></li>' 
         +'<li><label>Mercenary Armies <input type="checkbox" value="mercenary armies with you." class="bonus_select_option"></label></li>' 
         +'<li><label>Famed Hero <input type="checkbox" value="feasting with a famed hero!" class="bonus_select_option"></label></li>' 
         +'<li><label>Queen Parading <input type="checkbox" value="Queen is parading!" class="bonus_select_option"></label></li>' 
         +'<li><label>Wanted Criminal <input type="checkbox" value="caught a wanted criminal!" class="bonus_select_option"></label></li>' 
         +'<li><label>Rolling Logs <input type="checkbox" value="has extra logs!" class="bonus_select_option"></label></li>' 
         +'<li><label>Archery Game <input type="checkbox" value="holding a Archery game!" class="bonus_select_option"></label></li>' 
         +'</ul>' 
         +'</div>'); 

и вот пример сообщения заголовка строки: Лайам Аллан потребность героических товарищей!

я создавал массив значений CheckBox, как так:

var bonus = []; 
$("input.bonus_select_option:checked").each(function(){ 
    bonus.push($(this).val()); 
}); 

Что я хотел бы сделать сейчас, возьмите сообщения строки заголовка, и проверьте, содержит ли он какой-либо из значения массива, но им не удалось это сделать.

Любая помощь будет принята с благодарностью и благодарит заранее!

+0

Вы должны смотреть на Array.indexOf - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – Archer

+0

работал для меня Http: // jsfiddle. net/Sx9pU/ – Jai

+0

@Archer у меня была попытка использовать IndexOf, но мои значения массива содержат только часть строк, они не совсем одинаковы –

ответ

1

Try Array.join и String.search методы:

var re = new RegExp('(' + bonus.join('|') + ')'); 
console.log('Liam Allan is need of heroic companions!'.search(re) != -1); // true if contains 
0

Начиная с тем, как вы заполнили ваш бонус переменную:

var title = 'Liam Allan is need of heroic companions!'; 
    var bonus = []; 
    $("input.bonus_select_option:checked").each(function(){ 
     bonus.push($(this).val()); 
    }); 
    $.each(bonus, function(key, value){ 
     if(title.indexOf(value) > 0) ... //Do something 
    }); 

Например:

var title = 'Liam Allan is need of heroic companions!'; 
    var bonus = []; 
    bonus.push('heroic companions!'); 
    bonus.push('recruited swordsmen!'); 
    bonus.push('feasting with a famed hero!'); 

    $.each(bonus, function(key, value){ 
    if(title.indexOf(value) > 0) alert(value + " found in title"); 
    }); 

бы возврат

heroic companions! found in title 
Смежные вопросы