[英]Is there any better way to handle this function with multiple if statements doing almost the same?
我有這個功能:
private addAdditionalResults(resultsToAdd: any) {
if(!isNaN(resultsToAdd.xx) && this.x.length > 0)
this.x.unshift(resultsToAdd.xx);
if(!isNaN(resultsToAdd.yy) && this.y.length > 0)
this.y.unshift(resultsToAdd.yy);
if(!isNaN(resultsToAdd.zz) && this.z.length > 0)
this.z.unshift(resultsToAdd.zz);
}
x,y,z是數字數組。 resultsToAdd是一個對象,其變量xx,yy,zz可能與NaN不同。 無論如何,可以使此代碼更漂亮嗎? 這些if語句的作用幾乎相同。
如果您事先知道鍵並且它們遵循一個模式,則可以通過以下方式將其縮短:
var variables = ['x','y','z'];
var that = this;
for (var key in variables) {
if (!isNaN(resultsToAdd[key + key]) && that[key].length > 0) {
that[key].unshift(resultsToAdd[key + key])
}
}
您可以在函數內部使用數組創建變量,然后對其進行迭代。 但這會因為循環而影響您的程序響應。
results = array(resultsToAdd.xx, resultsToAdd.yy, resultsToAdd.zz);
numbers = array(this.x, this.y, this.z);
for(i = 0; i < results.length; i++){
if(!isNaN(results[i]) && numbers[i] > 0)
numbers[i].unshift(results[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.