admin管理员组

文章数量:1417031

Could someone tell me how to get alternate values from a range of values, through Angular js?

monthDataCreation(){
    var startDay =1;
    var endDay = 10;
    for (var a = startDay; a < endDay; a++) {
        var element = a;
        console.log("list values like 1,2,5,7,9... ")
    }
} 

what I need is if I set a start value and end value and on loop it I should get alternate values.

If it start with even num 2 ends at 10 then the string of alternate value should be 2,4,6,8,10.

If it start with odd num 1 ends at 10 then the string of alternate value should be 1,3,5,7,9

Is there any angular way of solution

Could someone tell me how to get alternate values from a range of values, through Angular js?

monthDataCreation(){
    var startDay =1;
    var endDay = 10;
    for (var a = startDay; a < endDay; a++) {
        var element = a;
        console.log("list values like 1,2,5,7,9... ")
    }
} 

what I need is if I set a start value and end value and on loop it I should get alternate values.

If it start with even num 2 ends at 10 then the string of alternate value should be 2,4,6,8,10.

If it start with odd num 1 ends at 10 then the string of alternate value should be 1,3,5,7,9

Is there any angular way of solution

Share Improve this question edited Aug 4, 2020 at 6:39 Safwan Samsudeen 1,7072 gold badges12 silver badges27 bronze badges asked Jul 21, 2017 at 9:12 Yokesh VaradhanYokesh Varadhan 1,6364 gold badges21 silver badges48 bronze badges 1
  • 2 In place of a++ use a = a+2 in for loop. – Shubham Commented Jul 21, 2017 at 9:13
Add a ment  | 

4 Answers 4

Reset to default 2

I think you could simply change a++ to a+=2 to achieve the desired output. You then have to change a < endDay to a <= endDay though.

You can use the filter method of Array

var original  = [1, 2, 3, 4, 5, 6, 7, 8];
var alternate = original.filter(function(val,idx) {
  if(idx%2==0)
    return val;
})
console.log(alternate)

function monthDataCreation(start, end) {
    var values = []
    for (var i = start; i <= end; i += 2) {
        values.push(i)
    }
    return values.join(', ')
}

monthDataCreation(1, 10) will return "1, 3, 5, 7, 9"

monthDataCreation(2, 10) will return "2, 4, 6, 8, 10"

const a = [1, 2, 3, 4, 5, 6]
    for (let i = 0; i < a.length; i++) {
        if (i % 2 == 0) {
            console.log(a[i])
        }
    }

本文标签: javascriptGet alternate values of an arrayStack Overflow