这里如何使用扩展语法将数字转换为字符串数组?
How is the spread syntax used here to turn a number to a string array?
我试图解决其中一个编码网站上的挑战,我在该挑战的最佳解决方案中看到了这一点。
有人可以详细说明为什么这段代码:[...a%10+''+a]
returns 以下数组:["2", "1", "1", "2", "2"]
幕后究竟发生了什么?
P.S。我知道这可能不是最佳做法,但我仍在学习,这看起来真的很有趣。
假设a
的原始值为1122
。
a%10
returnsa
的最后一位,即2
.
+''
将其从数字转换为字符串,"2"
.
+a
连接 a
的完整值,得到 "21122"
.
- 将其放入
[...]
中会将字符串展开到其字符数组中。
以下是代码中的所有步骤:
const a = 1122;
const lastDigit = a % 10;
const lastDigitStr = lastDigit + '';
const newStr = lastDigitStr + a;
const result = [...newStr];
console.dir(result);
我试图解决其中一个编码网站上的挑战,我在该挑战的最佳解决方案中看到了这一点。
有人可以详细说明为什么这段代码:[...a%10+''+a]
returns 以下数组:["2", "1", "1", "2", "2"]
幕后究竟发生了什么?
P.S。我知道这可能不是最佳做法,但我仍在学习,这看起来真的很有趣。
假设a
的原始值为1122
。
a%10
returnsa
的最后一位,即2
.+''
将其从数字转换为字符串,"2"
.+a
连接a
的完整值,得到"21122"
.- 将其放入
[...]
中会将字符串展开到其字符数组中。
以下是代码中的所有步骤:
const a = 1122;
const lastDigit = a % 10;
const lastDigitStr = lastDigit + '';
const newStr = lastDigitStr + a;
const result = [...newStr];
console.dir(result);