51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

如何在 TypeScript 中使用 `let` 将单个值分配给多个变量名?

英文:

How to assign single value to multiple variable name using let in typescript

问题 {#heading}

我正在尝试在 TypeScript 中为所有变量名称分配一个值。但不起作用。如何分配它。

let name1, name2, name3, name4 = false;

console.log(name1, name2, name3, name4);

演示:https://stackblitz.com/edit/github-7plax5-gpafmb?file=src%2Fapp%2Fapp.component.ts 英文:

I am trying to assign one value to all variables names in typescript. But not working .How to assign it.

let name1,name2,name3,name4 = false;
`console.log(name1,name2,name3,name4);
`

Demo: https://stackblitz.com/edit/github-7plax5-gpafmb?file=src%2Fapp%2Fapp.component.ts

答案1 {#1}

得分: 4

我会填充一个数组并解构它以将所有变量分配给相同的值。 英文:

I would fill an array and destructure it to assign all variables to the same value.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let [name1, name2, name3, name4] = Array(4).fill(false);
`console.log(name1, name2, name3, name4);
`

<!-- end snippet -->

答案2 {#2}

得分: 3

不要把它搞得太复杂

let name1 = false;
let name2 = false;
let name3 = false;
let name4 = false;

在你的IDE中,使用多个光标很容易阅读并且运行良好。 英文:

Don't overcomplicate it

let name1 = false;
let name2 = false;
let name3 = false;
let name4 = false;

It's readable and works well with multiple cursors in your IDE

答案3 {#3}

得分: 1

你只能在两行内完成它:

let name1, name2, name3, name4;
name1 = name2 = name3 = name4 = false;
console.log(name1, name2, name3, name4);

Playground 英文:

You can only do it in a 2 liner :

let name1,name2,name3,name4;
name1 = name2 = name3 = name4 = false;
console.log(name1, name2, name3, name4)

Playground


赞(0)
未经允许不得转载:工具盒子 » 如何在 TypeScript 中使用 `let` 将单个值分配给多个变量名?