2017-10-19 112 views
1

我有一個對象數組,並且有可能包含整數或字符串的屬性id。我正在使用該屬性進行比較,但現在我猜測,如果始終將整數轉換爲整數id(即使它是整數)或詢問它是否爲字符串並將其轉換,效率會更高。我的意思是這樣的:javascript將int值解析爲int

let myArray = [{id: 1, ...otherprops}, {id: 2, ...otherprops}, {id: '3', ...otherprops}, {id: '4', ...otherprops}]; 

這是更有效的...

for (let x of myArray) { 
    if (parseInt(x.id, 10) === 3) { 
     ... 
    } 
} 

或者驗證碼:

for (let x of myArray) { 
    let id = -1; 
    if (typeof x.id === 'string') { 
     id = parseInt(x.id, 10); 
    } 
    if (id === 3) { ... } 
} 

因爲第一代碼轉換總是我不知道,如果兩個條件更好。

+0

@Bian Goole - [tag:parsing]標籤與字符串轉換爲數字類型無關;請在添加標籤之前閱讀標籤的預期用途...... –

+0

@DavidBowling我很欣賞您的評論,這是我發現的一種快速解決方案。我現在正在閱讀你的建議。 – assembler

回答

3

如果您知道,您只有數字或絃樂號碼,那麼您可以將unary plus +轉換爲數字,但不會更改數字。

var id = +x.id; 
+0

就是這樣,它解決了這個問題......我不知道......謝謝 – assembler