如何用打字法把两个数字相加

how to sum 2 numbers in typescript

本文关键字:两个 数字 何用打      更新时间:2023-09-26

我有这个属性

export interface IOurFirstSpfWebPartWebPartProps {
  description: string;
  n1: number;
  n2: number;
}

然后我有这个方法

public render(): void {
    this.domElement.innerHTML = `
      <div class="${styles.ourFirstSpfWebPart}">
        <div class="${styles.container}">
          <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
            <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
              <span class="ms-font-xl ms-fontColor-white">Welcome to SharePoint!</span>
              <p class="ms-font-l ms-fontColor-white">Customize SharePoint experiences using Web Parts.</p>
              <p class="ms-font-l ms-fontColor-white">${this.properties.n1} + ${this.properties.n2}</p>
              <a href="https://github.com/SharePoint/sp-dev-docs/wiki" class="ms-Button ${styles.button}">
                <span class="ms-Button-label">Learn more</span>
              </a>
            </div>
          </div>
        </div>
      </div>`;
  }

然而,这是打印1+2而不是3。

为要添加的每个参数添加一个额外的+。你需要这样做:this.sum = +this.num1 + +this.num2;

您的答案与javascript中的隐式强制有关。简单地说,您在模板中插入两个字符串,而不是添加两个数字。

当您在模板语法中达到{}时,您的数字将被字符串化。本质上,你是在添加

"1"+"2"="12">

而不是

1+2=3

你可以尝试两件事:

  1. 将两个表达式都放在{}中

${this.properties.n1 + this.properties.n2}

如果这仍然是"12",那么

  1. 尝试${parseInt(this.properties.n1) + parseint(this.properties.n2)}。如果可以的话,这将首先将两个值强制为一个数字

你可以在You Don't Know JS:Types&Grammar,它将真正解释关于+运算符和隐式类型的所有"gotchas"。

勾号标记创建一个模板文字。我想你在寻找:${this.properties.n1 + this.properties.n2}——都在同一个大括号内。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

在数字前面加一个+号