gpt4 book ai didi

javascript - typescript 。如何在 foreach 循环 : "left-hand side of an arithmetic operation must be of type ' any', 'number' 或枚举类型中避免此错误”?

转载 作者:搜寻专家 更新时间:2023-10-30 21:16:46 24 4
gpt4 key购买 nike

这是 javascript 或 typescript foreach 的一种非常常见的用法:

myArray = ["a","b","c"]

for(var index in myArray)
console.log(myArray[index])

代码日志:a b 和 c

但是在 typescript 中,“索引”变量被认为是一个字符串。 .当我进行任何计算时,例如 index*2,TS compuler 显示休闲编译器错误:

for(var index in myArray)
console.log(index * 2); // TS compiler error.

Error TS2362 The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type

但在执行时记录 0,2 和 4(如预期的那样)

如何避免或抑制此错误?

最佳答案

index 是一个字符串。 for..in遍历对象的键。碰巧数组的键是数字的。尽管如此,它们仍存储为字符串。

检查一下:

var myArray = [1, 2, 3];
for (var index in myArray) {
console.log(typeof index);
}

还值得注意的是,无法保证顺序您将获得这些 key 。通常它们会以正确的顺序出现,但您得到 "3"、"1"、"2" 并不是无效的,例如。

相反,只需使用普通的 for loop.然后你的索引将是数字,你会确定你正在按顺序在数组中移动。

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);
});

关于javascript - typescript 。如何在 foreach 循环 : "left-hand side of an arithmetic operation must be of type ' any', 'number' 或枚举类型中避免此错误”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com