这是我编写的代码:
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/