Javascript 如何增加每10个元素的计数器
我需要写一个逻辑,在每10个元素之后增加计数器。i、 第十、二十等。如果有超过10个元素,计数器将增加到1,如果大于20,计数器值将变为2Javascript 如何增加每10个元素的计数器,javascript,Javascript,我需要写一个逻辑,在每10个元素之后增加计数器。i、 第十、二十等。如果有超过10个元素,计数器将增加到1,如果大于20,计数器值将变为2 const ele = 10; // possible values 10, 20, 30 let counter = 0; if(ele.lemgth > 10){ counter++ } console.log(counter) // logs 1 enter code here 请提供任何建议。您似乎需要: const count = 3
const ele = 10; // possible values 10, 20, 30
let counter = 0;
if(ele.lemgth > 10){
counter++
}
console.log(counter) // logs 1
enter code here
请提供任何建议。您似乎需要:
const count = 35;
const every = 10;
let counter = 0;
for(let i=0; i<=count; i+=every) {
counter++
}
const count=35;
常数=10;
设计数器=0;
对于(设i=0;i,您可以将元素数除以10。
如果您想容纳您提议的10、20、30之间的值,可以使用math.floor()进行四舍五入。
const ele=10;//可能的值10、20、30
让计数器=数学楼层(ele/10);
console.log(计数器);
const items=[1,2,3,4,5等];
常数=10;
设计数器=0;
for(设i=0;i
这样,Y总是有正确的计数器。如果ele=120,计数器=12,如果ele=10,计数器=1
var-ele=120;
设计数器=0;
计数器=数学楼层(ele/10);
控制台日志(计数器);
让数组=[]//任何数组都可以放在这里
设计数器=0;
//检查数组的长度是否可以被10整除
if(array.length%10==0){
//如果数组可以被10整除,则不需要循环遍历它
//将数组的长度除以10
计数器=数组长度/10;
}否则{
//如果数组不能被10整除,
//在10次迭代中运行一个循环以获得正确的计数器
对于(让i=0;听起来你需要循环?你可以做counter+=Math.floor(ele/10)
?您也不需要对一个数字调用.length
。如果它实际上是一个数字?当元素数低于10时,您的逻辑将计数器设置为1。0-10应该输出0 11-20应该输出1 etcah man,有时我会因为无法想出一个明显的解决方案而感到非常愚蠢。非常感谢,如果你解释了你提供的代码是如何回答这个问题的。我编辑了我的答案来解释逻辑。希望这能有所帮助。
const items = [1,2,3,4,5, ... etc];
const ele = 10;
let counter = 0;
for(let i = 0; i < items.length; i++) {
if ((i + 1) % 10 === 0 ) {
counter++;
}
}
let array = [] // any array could go here
let counter = 0;
//check to see if the length of the array is evenly divisible by 10
if(array.length % 10 === 0){
//if the array is divisible by 10, you don't need to loop through it
//divide the length of the array by 10
counter = array.length/10;
}else{
//if the array is not evenly divisible by 10,
//run a loop in iterations of 10 to get the correct counter
for(let i=0; i<=array.length; i+=10) {
counter++;
}
}