javascript - 当字段为空时如何动态更改数组字段的值

标签 javascript logic

这是我编写的代码:

for (let i = 0; i < result.length; i++) {
    if (result[i].mkp == ' ') {
        //the first time that a empty field happen
        //the array position is filled with "FRANQUIAS"
        result[i].mkp = "FRANQUIAS";
    }
    if (result[i].mkp == ' ') {
        //the second time that a empty field happen
        //the array position is filled with "TELEVENDAS"
        result[i].mkp = "TELEVENDAS";
    }
    if (result[i].mkp == ' ') {
        //the third time that a empty field happen
        //the array position is filled with "OCC"
        result[i].mkp = "OCC";
    }
}

但是我自己想不通如何才能达到将空字段更改为这三个字段的目的。有人可以帮助我吗?

最佳答案

保留一个额外的计数器变量,当出现空字段时该变量会递增。

// variable for keeping track of empty field
let c = 0;

for (let i = 0; i < result.length; i++) {
    // chek value or couter in addition to your condition
    if (c === 0 && result[i].mkp == ' ') {
        //the first time that a empty field happen
        //the array position is filled with "FRANQUIAS"
        result[i].mkp = "FRANQUIAS";
        // increment counter value whenever empty field occurs
        c++;
    }
    else if (c === 1 && result[i].mkp == ' ') {
        //the second time that a empty field happen
        //the array position is filled with "TELEVENDAS"
        result[i].mkp = "TELEVENDAS";
        c++;
    }
    else if (c === 2 && result[i].mkp == ' ') {
        //the third time that a empty field happen
        //the array position is filled with "OCC"
        result[i].mkp = "OCC";
        c++;
    }
}

您甚至可以通过使用包含这些值的数组来简化代码。

// variable for keeping track of empty field
let c = 0;
// array which contains the value
const val = [ 'FRANQUIAS', 'TELEVENDAS', 'OCC'];

for (let i = 0; i < result.length; i++) {
     // check counter is less than 3(update if there is more possibility or use c < val.length)
     // and check value is empty
     if (c < 3 && result[i].mkp == ' ') {
        // update value with corresponding value in array 
        // and increment, where `c++` returns current value and increments 
        result[i].mkp = val[c++];
    }
}

关于javascript - 当字段为空时如何动态更改数组字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55356031/

相关文章:

javascript - 网络浏览器未在 Windows Phone 8 上加载页面内容

javascript - 联系表单未发送 [html、php、js]

javascript - 根据函数参数返回嵌套对象值

javascript - Google App Engine Python、Jquery 和 Javascript 用于级联选择

javascript - 如何创建自动隐藏侧边栏

javascript - javascript 中的 return false 和 event.preventDefault 有什么不同?

logic - 表示 SMT-LIB 中的时间约束

c++ - 帮助 C++ 逻辑?

c# - 可能具有挑战性 : How do I implement solving logic in this puzzle solver program?

android - 如何在插入数据库时​​立即检索插入的值