How do I rewrite this using if…else clauses?
itemsArr.sort(function (a, b) {
return a.innerH开发者_运维问答TML == b.innerHTML ? 0 : (a.innerHTML > b.innerHTML ? 1 : -1);
});
I'd like to know how this function could be written with if & else syntax
itemsArr.sort(sortFunction);
function sortFunction (a, b) {
if (a.innerHTML == b.innerHTML) return 0;
else if (a.innerHTML > b.innerHTML) return 1;
else return -1;
}
That would look like this:
itemsArr.sort(function(a, b) {
if (a.innerHTML == b.innerHTML) {
return 0;
} else if (a.innerHTML > b.innerHTML) {
return 1;
} else {
return -1;
}
});
You can also write it without else
, as the return
will exit the function:
itemsArr.sort(function(a, b) {
if (a.innerHTML == b.innerHTML) return 0;
if (a.innerHTML > b.innerHTML) return 1;
return -1;
});
function isGreater(a,b){
if(a.innerHTML == b.innerHTML){
return 0;
} else if(a.innerHTML > b.innerHTML){
return 1;
}else{
return -1;
}
}
But why you want to do this?
function(a, b) {
returnType returnValue;
if(a.innerHTML == b.innerHTML){
returnValue = 0;
}else if(a.innerHTML > b.innerHTML){
returnValue = 1
}else{
returnValue = -1
}
return returnValue;
}
精彩评论