最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I assign multiple variables the same value without having one line per variableassignment? - Stack Overflow

programmeradmin1浏览0评论

I am looking for a less verbose way to instantiate multiple variables to the same value. I currently have this:

let a = 0;
let b = 0;
let c = 0;
let d = 0;
let e = 0;
let f = 0;
let g = 0;
let h = 0;
let i = 0;
let j = 0;
let k = 0;
let l = 0;
let m = 0;
let n = 0;
let o = 0;

And I am looking to do something like this:

let { a, b, c, d, e, f, g, h, i, j, k, l, m, n, o } = 0;

All these variables return undefined. There surely has to be a better way to instantiate multiple variables to the same value? I am using let as these values change over time.

I am looking for a less verbose way to instantiate multiple variables to the same value. I currently have this:

let a = 0;
let b = 0;
let c = 0;
let d = 0;
let e = 0;
let f = 0;
let g = 0;
let h = 0;
let i = 0;
let j = 0;
let k = 0;
let l = 0;
let m = 0;
let n = 0;
let o = 0;

And I am looking to do something like this:

let { a, b, c, d, e, f, g, h, i, j, k, l, m, n, o } = 0;

All these variables return undefined. There surely has to be a better way to instantiate multiple variables to the same value? I am using let as these values change over time.

Share Improve this question edited Mar 13, 2020 at 16:00 TylerH 21.1k77 gold badges79 silver badges112 bronze badges asked Mar 13, 2020 at 12:14 user3180997user3180997 1,9263 gold badges21 silver badges37 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 12

You could destructure your variables as an array as follows, though you need to know the number of elements, and it does require ES6+:

let [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = Array(15).fill(0);

Here's what I would do.

const [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = repeat(0);

console.log(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);

function* repeat(x) {
    while (true) yield x;
}

Related question: How to use destructuring assignment to define enumerations in ES6?

You could take a generator which yields the wanted value for a destructuring with an array.

function* always(v) {
    while(true) yield v;
}

let [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = always(0);

console.log(a);
console.log(o);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论