在JavaScript中同时处理多个变量

huangapple go评论53阅读模式
英文:

Working with a number of variables at a time in JavaScript

问题

可以使用一个数组和循环来更简洁地应用toFixed(prec)函数到这些变量上,如下所示:

var variables = [x1, x2, y1, y2, a1, a2, b1, b2, c1, c2];
for (var i = 0; i < variables.length; i++) {
  variables[i] = variables[i].toFixed(prec);
}

这段代码将所有的变量存储在一个数组中,然后通过循环遍历数组中的每个变量,分别应用toFixed(prec)函数。

英文:

I have these 10 variables already declared and they each contain a float value.

Is there any way to apply the function toFixed(prec) with prec as the parameter to all these variables with a shorter code? Using an array or something like that?

x1 = x1.toFixed(prec);
x2 = x2.toFixed(prec);
y1 = y1.toFixed(prec);
y2 = y2.toFixed(prec);
a1 = a1.toFixed(prec);
a2 = a2.toFixed(prec);
b1 = b1.toFixed(prec);
b2 = b2.toFixed(prec);
c1 = c1.toFixed(prec);
c2 = c2.toFixed(prec);

答案1

得分: 2

把变量放入一个数组中,进行映射和解构:

[x1, x2, y1, y2, ...] = [x1, x2, y1, y2, ...].map(num => num.toFixed(prec));
英文:

Put the variables into an array, map it and destructure:

[x1, x2, y1, y2, ...] = [x1, x2, y1, y2, ...].map(num =&gt; num.toFixed(prec));

答案2

得分: 1

是的,你应该将所有这些参数保存在一个对象中(在其他语言中可能是一个关联数组),然后你可以简单地循环遍历该对象。

/**
替换这部分:
x1=x1.toFixed(prec);
x2=x2.toFixed(prec);
y1=y1.toFixed(prec);
y2=y2.toFixed(prec);
a1=a1.toFixed(prec);
a2=a2.toFixed(prec);
b1=b1.toFixed(prec);
b2=b2.toFixed(prec);
c1=c1.toFixed(prec);
c2=c2.toFixed(prec);

使用这个:
*/

let options = {
  x1: 1.0,
  x2: 2.0,
  x3: 3.0,
}

console.log('Before', options);

for (const [key, value] of Object.entries(options)) {
  options[key] = value.toFixed(3);
}

console.log('After', options);
英文:

Yes, you should keep all these parameters in object (as associative array in other language), than you can simply loop that object.

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

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

/**
Replace this:
x1=x1.toFixed(prec);
x2=x2.toFixed(prec);
y1=y1.toFixed(prec);
y2=y2.toFixed(prec);
a1=a1.toFixed(prec);
a2=a2.toFixed(prec);
b1=b1.toFixed(prec);
b2=b2.toFixed(prec);
c1=c1.toFixed(prec);
c2=c2.toFixed(prec);

with this:
*/

let options = {
  x1: 1.0,
  x2: 2.0,
  x3: 3.0,
}

console.log(&#39;Before&#39;, options);

for (const [key, value] of Object.entries(options)) {
  options[key] = value.toFixed(3);
}

console.log(&#39;After&#39;, options);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月17日 15:59:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定