Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

How can I skip a specific Index in an array in a for loop javascript

Suppose I had a function that is pulling in values from somewhere and storing those values into an array.

function getSport(ply) {
   some code here... //function gets values that I need for array later
}

var sports1 = getSport(playerChoice); 
var sports2 = getSport(playerChoice);
var sports3 = getSport(playerChoice);
var sports4 = getSport(playerChoice);

var sportsArry = [sports1, sports2, sports3, sports4];

Now I would like to use a for loop to loop the elements, the problem, however, is the first index (index 0) will always be true. I want to skip index 0. How do I do that? Further I want to replace index 0 with something else. Let me show you

for (var i = 0; i<sportsArry.length; i++){
  if ( (sports1 == sportsArry[i])  ) {
     sports1 = null;   //I figured I should null it first?
     sports1 = replaceValueFunc(playerChoice2);
  }
}  

Well you can see the problem I would have. Index 0 is true.

Let me show you what would work, although it requires alot of or operators.

if ( (sports1 == sportsArry[1]) || (sports1 == sportsArry[2]) || (sports1 == sportsArry[3] ) {

... }

^^ That is one way to skip index 0, what would be another better looking way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I want to skip index 0. How do I do that? Further I want to replace index 0 with something else.

Just start the loop from 1 instead of 0

sportsArr[0] = "Something else"; // set the first element to something else
for(var i = 1; i < sportsArr.length; i++){ 
   // do something
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...