IndexOf整个数组和警报名称

时间:2013-03-08 09:13:51

标签: javascript arrays loops for-loop indexof

我正在尝试在html文件中编写以下javascript。

创建一个包含10个运动队名称的数组。

然后使用“for循环”循环遍历数组。如果团队名称包含字母“an”,则提醒团队名称。我想使用“indexOf”函数来确定团队名称中是否包含“an”。

这是我走了多远:

    // index:                                   
    var NHL = new Array("New Jersey Devils", "New York Islanders", 
                       "New York Rangers", "Philadelphia Flyers", 
                       "Pittsburgh Penguins", "Boston Bruins", 
                       "Buffalo Sabres", "Montreal Canadiens" , 
                       "Ottawa Senators", "Toronto Maple Leafs");

    for( i=0 , i<NHL.indexOf("an") , i++ ){
      if(NHL.indexOf == "an"){
          alert(indexOf)
      }
    }

4 个答案:

答案 0 :(得分:1)

indexOf(str)将返回非负索引。如果子字符串不存在,它将返回-1,否则它将返回该str的第一次出现。

var NHL = new Array("New Jersey Devils", "New York Islanders", 
          "New York Rangers", "Philadelphia Flyers", "Pittsburgh Penguins", 
          "Boston Bruins", "Buffalo Sabres", "Montreal Canadiens" , 
          "Ottawa Senators", "Toronto Maple Leafs"); 

for(i=0; i<NHL.length; i++)
{
    if(NHL[i].indexOf("an") !== -1)
        alert(NHL[i]);
}

答案 1 :(得分:1)

var NHL = new Array("New Jersey Devils", "New York Islanders", "New York Rangers", "Philadelphia Flyers", "Pittsburgh Penguins", "Boston Bruins", "Buffalo Sabres", "Montreal Canadiens" , "Ottawa Senators", "Toronto Maple Leafs");

for(var i=0, len=NHL.length; i<len; i++ ){
  var name=NHL[i];
  if(name.indexOf("an")>-1){
      alert(name);
  }
}

答案 2 :(得分:0)

var NHL = new Array("New Jersey Devils", "New York Islanders", 
"New York Rangers", "Philadelphia Flyers", "Pittsburgh Penguins", 
"Boston Bruins", "Buffalo Sabres", "Montreal Canadiens" , 
"Ottawa Senators", "Toronto Maple Leafs"); 

/** 
 * Iterate through each array element,
 * Check against 'an', indexOf returns -1
 * if no match found.
**/
for( var i=0 ; i < NHL.length; i++ ) {
     if ( NHL[i].indexOf("an") !== -1 ) 
            alert( "This " + NHL[i] + " Contains 'an' at array index: " + i );
}

jsFiddle http://jsfiddle.net/HqXSs/1/

答案 3 :(得分:0)

你走了:

var NHL = new Array("New Jersey Devils", "New York Islanders", "New York Rangers", "Philadelphia Flyers", "Pittsburgh Penguins", "Boston Bruins", "Buffalo Sabres", "Montreal Canadiens" , "Ottawa Senators", "Toronto Maple Leafs");

for (var i=0; i<NHL.length; i++){
    if(NHL[i].indexOf("an") !== -1){
        alert(NHL[i]);
    }
}