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

时间:2019-03-26 11:28:03

标签: 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";
    }
}

但是我自己无法弄清楚如何实现将空白字段更改为这三个字段的目的。有人可以帮我吗?

2 个答案:

答案 0 :(得分:3)

保留一个附加的计数器变量,该变量在发生空字段时递增。

// 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++];
    }
}

答案 1 :(得分:2)

您可以使用generator作为替换值,然后将mapspread syntax结合使用:

const input = [{ mkp: 'not empty' }, { mkp: ' ' }, { mkp: ' ' }, { mkp: 'something' }, { mkp: ' ' }, { mkp: 'something else' }];

const replacement = (function* () {
  yield 'FRANQUIAS';
  yield 'TELEVENDAS';
  yield 'OCC';
})();

const result = input.map(o => ({ ...o, mkp: o.mkp === ' ' ? replacement.next().value : o.mkp }));
console.log(result);