gpt4 book ai didi

javascript - Typeof 返回 "number",但日志记录变量显示字符串

转载 作者:行者123 更新时间:2023-11-30 20:53:21 24 4
gpt4 key购买 nike

我将数值从 Angular 应用程序中的表单传递到服务中的方法。我的单元测试检查值的类型并期望它们是“数字”。它通过了。

但是,当我 console.log 值(传递给方法之前和之后)时,它们显示为字符串,例如“10”。即使在方法功能内部,我也可以看到它们被视为字符串,例如90 + 180 = "90180"。

为什么 typeof 返回“number”?

(我已经通过使用 +variable 将值作为数字传递来解决这个问题,我只是想知道为什么当类型不是数字时 typeof 返回“数字”。)

我正在使用 jasmine 进行单元测试,这是我的测试:

it("coverageParams.heading, .swathWidth, and .impWidth should be typeof 'number'", () => {
// Patching numerical values into the form
component.fieldCoverageParamsForm.patchValue({
heading: 30,
impWidth: 10,
swathWidth: 20
});
fixture.detectChanges();

// Method in the component snippet below
component.createCoveragePath();
expect(typeof component.coverageParams.heading).toBe("number");
expect(typeof component.coverageParams.swathWidth).toBe("number");
expect(typeof component.coverageParams.impWidth).toBe("number");
});

这是我的组件:

export class FieldCoverageParamsComponent {

public fieldCoverageParamsForm: FormGroup;

public coverageParams: ICoverageParams;

constructor(
private routePlanner: RoutePlanningService,
private formBuilder: FormBuilder
) {
this.coverageParams = {
boundary: null,
heading: 0,
impWidth: 0,
startPoint: null,
swathWidth: 0
};
this.createForm();
}

public createCoveragePath() {
const formModel = this.fieldCoverageParamsForm.value;
this.coverageParams = {
boundary: formModel.boundary,
heading: formModel.heading,
impWidth: formModel.impWidth,
startPoint: formModel.startPoint,
swathWidth: formModel.swathWidth
};

this.routePlanner.plotRoute(
this.mapService.mainMapViewer,
this.coverageParams
);
}
}

最佳答案

However, when I console.log the values (both before and after passing to the method)

我假设您的意思是在您的实际代码中而不是在测试中。您在测试中修补数值,所以它真的很简单:

let heading = 10;
component.createCoveragePath();
expect(typeof heading).toBe("number");

这是真的,因为您正在修补中的数值。

当 Angular 实际运行时,表单输入的值将以字符串形式输出。你在这里得不到类型安全...... .valueany 类型,所以它返回为 {heading: "10"}

您可能希望在表单中使用 input type=number,因为在这种情况下,值返回为 number。否则,您将不得不像以前一样自己进行转换。

您还可以更新您的测试以修补字符串值或其他非数字值。

关于javascript - Typeof 返回 "number",但日志记录变量显示字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47930169/

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