foreach js syntacs code example

Example 1: for each js

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits below

// Normal way
fruits.forEach(function(fruit){
  console.log('I want to eat a ' + fruit)
});

Example 2: foreach jas

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

Example 3: js get index from foreach

var myArray = [123, 15, 187, 32];

myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
});

// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32

Example 4: foreach js

// result.params.detail = {
// "status": true,
// "message": "",
// "params": {
//     "pay_credit_remain": 115,
//     "month_expiry": "15",
//     "detail": [
//         {
//             "credit": "70",
//             "create_date": "2020-10-16",
//             "expiry_date": "2022-01-16"
//         },
//         {
//             "credit": "45",
//             "create_date": "2020-10-17",
//             "expiry_date": "2022-01-17"
//         }
//     ]
// }
//}

                 
detail = "<ul>";
result.params.detail.forEach((val) => {
  detail = detail + sprintf(lang.pay_credit_detail, val.credit, val.expiry_date);
});
detail += "</ul>";

$('#pay_credit_remain').html(detail);