![](/img/trans.png)
[英]get error The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type
[英]Typescript. How to avoid this error in foreach loop: “left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type”?
這是javascript或typescript foreach的一種非常常見的用法:
myArray = ["a","b","c"]
for(var index in myArray)
console.log(myArray[index])
代碼記錄:ab和c
但是在typescript中,“index”var被認為是一個字符串。 。 當我進行任何計算時,例如索引* 2,TS計算器顯示以下編譯錯誤:
for(var index in myArray)
console.log(index * 2); // TS compiler error.
錯誤TS2362算術運算的左側必須是“any”,“number”或枚舉類型
但在執行時記錄0,2和4(如預期的那樣)
如何避免或抑制此錯誤?
index
是一個字符串。 for..in
迭代對象的鍵。 恰好是數組的鍵是數字的。 不過,它們仍然存儲為字符串。
看一下這個:
var myArray = [1, 2, 3]; for (var index in myArray) { console.log(typeof index); }
值得注意的是,您無法保證獲得這些密鑰的訂單 。 通常它們會以正確的順序出現,但對於你來說,獲得"3", "1", "2"
並不是無效的。
相反,只需使用正常的for
循環。 然后你的索引將是數字,你肯定知道你正在按順序移動數組。
var myArray = [1, 2, 3]; for (var i = 0; i < myArray.length; i++) { console.log(typeof i, myArray[i]); }
您也可以使用forEach
運行它。
var myArray = [1, 2, 3]; myArray.forEach(function(val, index) { console.log(typeof index, val); });
它是一個字符串,你可以在其上調用parseInt(index, 10)
。 這是因為對象的索引總是字符串,即使在數組上,數組也有一些額外的行為來處理看起來像整數的鍵
但是,請注意,迭代數組的方式容易出錯。 請參閱https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
注意:for ... in不應該用於迭代索引順序很重要的數組。
無法保證元素將按順序迭代
您始終可以強制轉換元素以避免錯誤
console.log(index as number * 2); /
考慮到您的“索引”將是一個數字,您可以通過將索引轉換為數字類型來抑制警告/錯誤
for(var index in myArray)
console.log(Number(index) * 2);
另外
for(var index in myArray)
console.log(parseInt(index) * 2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.