0

我正在尝试在 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

4 回答 4

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]);
}
于 2013-03-08T09:18:20.720 回答
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);
  }
}
于 2013-03-08T09:21:24.360 回答
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/

于 2013-03-08T09:19:20.987 回答
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]);
    }
}
于 2013-03-08T09:21:20.023 回答