我在翡翠中有2个数组,它们的长度大小不同,我只想验证id是否相同,以便选择它们,而其他则不是
// jsCategory length 6
var jsCategory = array1
// jsCategory length 3
var jsMy = array2
var html_option = '';
for (var i = 0; i < jsCategory.length; i++) {
for (var z = 0; z < jsMy.length; z++) {
if (jsCategory[i]._id == jsMy[z]._id) {
//Correct
html_option += '<option value=' + jsCategory[i]._id + ' selected>' + jsCategory[i].name + '</option>';
} else {
//Not Select err
console.log(jsCategory[i]);
}
}
}
document.write(html_option);
答案 0 :(得分:0)
使用过滤器和减少操作
const findById = inWhere => ({ _id }) => !!inWhere.find(t => t._id === _id)
const html_option = array1
.filter(findById(array2))
.reduce((html, ({_id, name}) =>
html += `<option value=${_id} selected>${name}</option>`, ''))