尝试以下代码,但未获得预期的输出 我期望低于输出
[{"label":"one","value":"1","disabled":true},{"label":"two","value":"2","disabled":true},{"label":"three","value":"3","disabled":false},{"label":"four","value":"4","disabled":false},{"label":"five","value":"5","disabled":false},{"label":"six","value":"6","disabled":true}]
// ---
var A1 = [ {label:"one", value:"1"}, {label:"two", value:"2"}, {label:"six", value:"6"}];
var A2 = [ {label:"one", value:"1","disabled":false}, {label:"two", value:"2","disabled":false}, {label:"three", value:"3","disabled":false}, {label:"four", value:"4","disabled":false}, {label:"five", value:"5","disabled":false}, {label:"six", value:"6","disabled":false}];
for(let i = 0 ; i <A2.length; i++){
for(let j = 0; j < A1.length; j++){
if(A1[j].value == A2[i].value){
A2[i].disabled = true;
}
else{
A2[i].disabled = false;
}
}
}
console.log( JSON.stringify( A2 ) );
答案 0 :(得分:1)
如果我正确理解您要执行的操作,请执行以下操作:
for(let i = 0 ; i <A2.length; i++){
A2[i].disabled = false;
for(let j = 0; j < A1.length; j++){
if(A1[j].value == A2[i].value){
A2[i].disabled = true;
break;
}
}
}
也就是说-从false
值开始(没有匹配项),只有找到匹配项时才将其设置为true
。 (然后break
退出内循环,因为不需要继续。)
答案 1 :(得分:0)
如果需要的话,这里是一个替代的观点(jQuery选项)。这只是一个主意,因为我相信可以用更优美的方式写出来:)
var A1 = [ {label:"one", value:"1"}, {label:"two", value:"2"}, {label:"six", value:"6"}];
var A2 = [ {label:"one", value:"1","disabled":false}, {label:"two", value:"2","disabled":false}, {label:"three", value:"3","disabled":false}, {label:"four", value:"4","disabled":false}, {label:"five", value:"5","disabled":false}, {label:"six", value:"6","disabled":false}];
var tempA = new Array();
var resultArray = new Array();
$.each(A1,function(datakey,dataval){
tempA.push(dataval['label']);
});
$.each(A2,function(datakey,dataval){
if ($.inArray(dataval['label'],tempA)>-1) {
resultArray.push({'label':dataval['label'],'value':dataval['value'],'disabled':true})}
else {
resultArray.push({'label':dataval['label'],'value':dataval['value'],'disabled':false})
}
});
console.log(resultArray);