sortComponents (a, b) {
if (!a) {
return 1
}
if (!b) {
return -1
}
return this.keyedComponentTypes[a].text > this.keyedComponentTypes[b].text ? -1 : 1
},
有什么方法可以将前两个返回语句总结/简化为一个吗?我不想使用三元运算符将其更改为单语句并使代码变得复杂。
最佳答案
当条件和 !b
为 true 时,您可以使用 ||
语句返回 -1。`
我们还知道,如果 a
未定义 ( !a
),它将返回 1
,因此我们确保返回该 >a
是定义的,否则,我们返回 1。
let keyedComponentTypes = [
{
text: 'b'
},
{
text: 'a'
},
{
text: 'e'
},
{
text: 'd'
},
{
text: 'c'
},
]
function originalSortComponents (a, b) {
if (!a) {
return 1
}
if (!b) {
return -1
}
return keyedComponentTypes[a].text > keyedComponentTypes[b].text ? -1 : 1
}
function improvedSortComponent(a,b) {
return a && ((keyedComponentTypes[a].text > keyedComponentTypes[b].text) || !b) ? -1 : 1
}
let array = [0,undefined,1,2,3,undefined,4]
console.log(array.sort(originalSortComponents));
console.log(array.sort(improvedSortComponent));
您可以看到在这两种情况下它返回相同的内容。
关于javascript - 在js中重构一个排序函数的简单return语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59791011/