有没有办法在Javascript中优化两个for循环



当满足某些条件时,我需要通过客户端脚本显示alert()。但我无法打印记录编号,这将是用户的关键信息,即这些特定记录导致系统显示警报。我做了一个for循环,在其中我推送一个名为docNoArr的数组中的docNo(记录Id(的值。然后在另一个for循环中,我用我在docNoArr数组中推送的值触发了一个警报。有人能建议我一种更好的方法来优化代码的重复性吗。我的老师对DRY说:不要重复你自己。但在这里,我被困在如何不重复。

我的代码:

var docNoArr = [];
/* 1st For Loop */
for (var e = 0; e < count; e++) {
isApplied = rec.getSublistValue({
sublistId: subid,
fieldId: reqid,
line: e
});
if (isApplied == true) {
rectype = rec.getSublistValue({
sublistId: subid,
fieldId: 'custpage_am_rectype',
line: e
});
if (rectype == 'qcs') {
var supplierFld = rec.getValue({ fieldId: 'custpage_am_vendor' });
var docNoFld = rec.getSublistValue({
sublistId: subid,
fieldId: 'custpage_am_docnum',
line: e
});
var recomdSupplier = rec.getSublistValue({
sublistId: subid,
fieldId: 'custpage_am_supplier',
line: e
})
if (recomdSupplier != supplierFld) {
docNoArr.push(docNoFld);
}
}
}
}
/* 2nd For Loop */
for (var ee = 0; ee < count; ee++) {
isApplied1 = rec.getSublistValue({
sublistId: subid,
fieldId: reqid,
line: ee
});
if (isApplied1 == true) {
rectype1 = rec.getSublistValue({
sublistId: subid,
fieldId: 'custpage_am_rectype',
line: ee
});
if (rectype1 == 'qcs') {
var supplierFld1 = rec.getValue({ fieldId: 'custpage_am_vendor' });
var recomdSupplier1 = rec.getSublistValue({
sublistId: subid,
fieldId: 'custpage_am_supplier',
line: ee
});
if (recomdSupplier1 != supplierFld1) {
alert('Vendor selected in not recommended in ' + docNoArr + ' nPlease enter Correct Vendor!');
return false;
}
}
}
}

我不完全确定代码是做什么的,但看起来你创建了一个新数组只是为了获得警报的索引?

你能不能;

if (recomdSupplier != supplierFld) {
docNoArr.push(docNoFld);
alert('Vendor selected in not recommended in ' + docNoArr.length - 1 + ' nPlease enter Correct Vendor!');
}

您是否可以将记录存储在格式化的字符串中,而不是将它们放入数组中,因为它们已经从另一个循环中限定了?

此外,由于这个问题提到了性能,您可能想做时间戳,看看哪个循环实际上运行得更快,forEachfor (var e = 0; e < count; e++) {

console.time('for each');
data['results'].forEach(element => {
//do something
});
console.timeEnd('for each');
/* 1st for loop  here*/
if (docNoArr.length > 0) {
alert('Vendor selected is not recommended in ' + docNoArr.join(', ') + '.nPlease enter Correct Vendor!');
}
/* 2nd for loop not needed */

相关内容

  • 没有找到相关文章

最新更新