Javascript 如何在字段为空时更改数组字段的动态值
以下是我编写的代码:Javascript 如何在字段为空时更改数组字段的动态值,javascript,logic,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 (resu
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";
}
}
for(设i=0;i
但是我自己也弄不明白,我怎么能达到把空字段改成这三个字段的目的呢。有人能帮我吗?保留一个额外的计数器变量,当出现空字段时,它会递增
// 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++;
}
}
//用于跟踪空字段的变量
设c=0;
for(设i=0;i
您甚至可以通过使用包含这些值的数组来简化代码
// 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++];
}
}
//用于跟踪空字段的变量
设c=0;
//包含值的数组
const val=['frankuias'、'TELEVENDAS'、'OCC'];
for(设i=0;i
您可以使用a作为替换值,然后使用:
const input=[{mkp:'notempty'},{mkp:'},{mkp:'},{mkp:'something'},{mkp:'},{mkp:'something'}];
常量替换=(函数*(){
产生‘弗兰奎亚斯’;
产生“TELEVENDAS”;
收益率‘OCC’;
})();
const result=input.map(o=>({…o,mkp:o.mkp===''?replacement.next().value:o.mkp}));
控制台日志(结果)也许我做错了什么,但我只收到“FRANQUIAS”。这是代码:@MateusFernando:can u shareresult
数组数据在循环之前对不起,我把变量C放在for中,所以它总是0。我换了衣服,它开始工作了!谢谢你。@Rai谢谢你,伙计。。。我没注意到在他的密码里:)@MateusFernando,你也这么说了。只是我们两人几乎同时发表了评论。没有冒犯意味着buddy.with spread语法:input.map(o=>({…o,mkp:o.mkp===''?replacement.next().value:o.mkp}))代码>啊,非常好。答案更新,谢谢@PranavCBalan!现在看起来比以前好多了:)