简体   繁体   English

如何在for循环上设置多个限制:javascript

[英]How to set more than one limit on for loop : javascript

I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit) 我正在使用javascript数组,在这里我使用for循环来获取前三个结果。(没有.length限制)

Attempting to have something like 尝试拥有类似的东西

for(let a=0;a<usss.length || a<3;a++)

Simple 简单

var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}

problem 问题

var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}

The way around, 顺带一提

var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}

Real Question 真实问题

How can i avoid using extra if() condition in my last stated code? 我如何避免在上一次声明的代码中使用额外的if()条件?

I am sorry if its very basic question, i just stuck on it. 如果它是一个非常基本的问题,我很抱歉,我只是坚持下去。 Any help or information will be appreciated. 任何帮助或信息将不胜感激。 Thanks for your time. 谢谢你的时间。

This seems to work : 这似乎可行:

 var users = ['s','g','h','i']; var users2 = ['s','g']; for(let a=0;(a<3 && a<users.length) ;a++){ console.log(users[a]); } for(let a=0;(a<3 && a<users2.length);a++){ console.log(users2[a]); } 

There will be no way without using an if somewhere as you have to check the length of the value. 除非if某处使用if您将无法检查值的长度。

 var users = ['s','g','h','i']; // define the length value outside var length = users.length >= 3 ? 3 : users.length; for(let a=0; a < length; a++){ console.log(users[a]); } var users2 = ['s','g']; for(let a=0; a < length; a++){ console.log(users[a]); } // you can define it inside the for loop but it's not so nice for reading for(let a=0; a < (users.length >= 3 ? 3 : users.length); a++){ console.log(users[a]); } 

Maybe the nicest would be to create a function and pass the 3 as a maxLength parameter 也许最好的办法是创建一个函数并将3作为maxLength参数传递

 var logMax = function(users, maxLength, info) { let length = users.length >= maxLength ? maxLength : users.length; for(let a=0; a < length; a++){ console.log(info, ' => ' + users[a]); } } var users = ['s','g','h','i']; logMax(users, 3, 'first'); logMax(['s','g'], 3, 'second'); 

You could use also use Array.some() 您也可以使用Array.some()

Note: Check browser compatibility and/or use polyfill 注意:检查浏览器兼容性和/或使用polyfill

 [1, 2, 3, 4, 5, 6, 7].some((el, idx) => { console.log(el); return ++idx === 4; /* <-- return top 4 */ }); 

Its very simple, I think you just need to go through the length of the array. 它非常简单,我认为您只需要遍历数组的长度即可。

 var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
  console.log(users2[a]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM