How to make a foreach loop into javascript?

2019-09-18 06:14发布

问题:

I'm trying to make a Razor loop in Javascript. I've tried this code, but this wouldn't work. Nothing is displayed into the web-page.

Code:

$(function () {
        $('#container').highcharts({
            title: {
                text: 'Monthly Average Temperature',
                x: -20 //center
            },
            subtitle: {
                text: 'Source: WorldClimate.com',
                x: -20
            },
            xAxis: {
                categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
            },
            yAxis: {
                title: {
                    text: 'Temperature (°C)'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                valueSuffix: '°C'
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
                borderWidth: 0
            },
            series: [
@{int i=0, compte = Model.statistique.Count;}
                @foreach (var item in Model.statistique) {
                    <text>
                        {
                            name: '@(item.nomProcessus)',
                            data: [@(item.lundi), @(item.mardi), @(item.mercredi), @(item.jeudi), @(item.vendredi)]
                        }
                    </text>
                    if (i < compte) {
                        @:,
                    }
                    else
                    {
                        @:]
                    }
                    i++;
                }
});
});

Original code:

jsFiddle

How do I to make the foreach razor loop works into it, please?

Any brilliant idea?

回答1:

Try this

   series: [
            @foreach(var item in Model)
            {
                @:{ name: '@item.nomProcessus', data: [@(item.lundi), @(item.mardi), @(item.mercredi), @(item.jeudi), @(item.vendredi)] },
            }
]

Note: You don't need to worry about that last coma. It is acceptable.