gpt4 book ai didi

javascript - 合并多个(几乎)重复的每个语句

转载 作者:行者123 更新时间:2023-12-01 02:05:01 28 4
gpt4 key购买 nike

我有以下一组几乎相同的 each 语句。我需要添加大约 20 个遵循类似模式的内容。我正在尝试找出如何获取小变量并将它们更新为单个语句(而不是 20 次相同但略有不同的内容)。

$.each(mainData.name.source_values, function(index, val) {
$("#matrix_datatable").find('#mNames')
.append($('<td class="tableCells">')
.append(val.value + '</td>')
)
});
$.each(mainData.description.source_values, function(index, val) {
$("#matrix_datatable").find('#mDescription')
.append($('<td class="tableCells">')
.append(val.value + '</td>')
)
});
$.each(mainData.subtitle.source_values, function(index, val) {
$("#matrix_datatable").find('#mSubtitle')
.append($('<td class="tableCells">')
.append(val.value + '</td>')
)
});

正如您所看到的,每个中唯一不同的是name,description,subtitlemNames,mDescription,mSubtitle。我如何将其合并到一个语句中,该语句使用这两组“变量”的数组(或其他内容),其中包含我需要深入研究的所有 20 多个变量:

var $dataPoints = ['name','description','subtitle'];
var $tableIds = ['mNames','mDescription','mSubtitle'];

最佳答案

您可以提取函数以便Don't Repeat Yourself :

function append(id) {
return function(index, val) {
$('#matrix_datatable').find(id)
// if your value doesn't contain HTML, opt for this
.append($('<td>', { class: 'tableCells', text: val.value })
// if it contains html, replace `text` with `html`
);
};
}

$.each(mainData.name.source_values, append('#mName'));
$.each(mainData.description.source_values, append('#mDescription'));
$.each(mainData.subtitle.source_values, append('#mSubtitle'));

您还可以循环您的$.each:

for (let i = 0; i < 3; i++) {
$.each(mainData[$dataPoints[i]].source_values, append('#'+$tableIds[i]))
}

事实上,有很多方法可以重构这段代码!

关于javascript - 合并多个(几乎)重复的每个语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45487545/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com