如何解决打字稿:使用对象并用于...中
我将以下功能从JS转换为Typescript,并且效果很好。但是在行if (!(key * key) in frequencyCounter2) {
中,我得到了错误:"The left-hand side of an 'in' expression must be of type 'any','string','number',or 'symbol'."
我试图以数字形式键入密钥,但无济于事。使用打字稿时,此操作通常没有意义吗?
// The function same accepts two arrays and should return true if every value in the array has its corresponding
// value squared in the second array. The frequency of values must be the same.
function sameOn(arrA: number[],arrB: number[]): boolean {
// complexity O(n): If arr is 1000 lines,this runs 2000 times
if (arrA.length !== arrB.length) {
return false;
}
type CountType = {
[key: number] : number
}
const frequencyCounter1: CountType = {};
const frequencyCounter2: CountType = {};
for (const val of arrA) {
frequencyCounter1[val] = (frequencyCounter1[val] || 0) +1;
}
for (const val of arrB) {
frequencyCounter2[val] = (frequencyCounter2[val] || 0) +1;
}
for (const key in frequencyCounter1) {
if (!(key * key) in frequencyCounter2) {
return false;
}
if (frequencyCounter2[key * key] !== frequencyCounter1[key]) {
return false;
}
}
return true;
}
sameOn([1,2,3,2],[4,1,9,4]) // returns true
解决方法
此行:
if (!(key * key) in frequencyCounter2) {
在frequenceCounter2
中查找 boolean ,因为key * key
创建了一个数字,然后!number
将该数字转换为布尔值。
如果您要检查是否没有key * key
键,则需要更多()
:
if (!((key * key) in frequencyCounter2)) {
// ^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^−−−−−−−−−
或者实际上,您只需要重定位第一个)
:
if (!(key * key in frequencyCounter2)) {
// Not here −−−^−−−−−−−−−−−−−−−−−−−−^−− here
因为key * key
表达式的in
部分将在in
部分之前求值。
这听起来很像是原始JavaScript中的错误,它可以在"true"
中检查"false"
或frequencyCounter2
而不会引起任何抱怨。 :-)
重构的解决方案是:
export function sameOn(arrA: number[],arrB: number[]): boolean {
// complexity O(n): If arr is 1000 lines,this runs 2000 times
if (arrA.length !== arrB.length) {
return false;
}
type CountType = {
[key: number] : number
}
const frequencyCounter1: CountType = {};
const frequencyCounter2: CountType = {};
for (const val of arrA) {
frequencyCounter1[val] = (frequencyCounter1[val] || 0) +1;
}
for (const val of arrB) {
frequencyCounter2[val] = (frequencyCounter2[val] || 0) +1;
}
for (const key in frequencyCounter1) {
const squaredKey = Number(key)*Number(key);
if (!(String(squaredKey) in frequencyCounter2)) {
return false;
}
if (frequencyCounter2[squaredKey] !== frequencyCounter1[key]) {
return false;
}
}
return true;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。