gpt4 book ai didi

javascript - 用javascript写一个简单的解码函数

转载 作者:行者123 更新时间:2023-11-30 07:19:56 25 4
gpt4 key购买 nike

我是 javascript 的初学者,我尝试编写一个简单的解码函数。在这里:

function decode(text) {
let letter, count, i, result, letters;
result = "";
for (i = 0; i < text.length; i++) {
count = text[i];
if (typeof Number(count) === "number") {
count = Number(count);
console.log(count); // this line only for testing
letter = text[i + 1];
letters = letter.repeat(count);
result += letters;
console.log(result); // this line only for testing
} else {
result += text[i];
}
}
return result;
}
console.log(decode("v2rt3b2x"));

我需要帮助来理解为什么当 typeof Number(count) === "number"为 false 时没有跳过 if 子句。它返回这个:

NaN
VM708:12
VM708:8 2
VM708:12 rr
VM708:8 NaN
VM708:12 rr
VM708:8 NaN
VM708:12 rr
VM708:8 3
VM708:12 rrbbb
VM708:8 NaN
VM708:12 rrbbb
VM708:8 2
VM708:12 rrbbbxx
VM708:8 NaN

如我所说,我是初学者,所以请手下留情...

我得到了正确的答案,但我稍后会尝试找出为什么 count - 1 有效,现在我感谢大家的帮助。

function decode(text) {
let letter, count, i, result, letters;
result = "";
for (i = 0; i < text.length; i++) {
count = parseInt(text[i]);
if (!isNaN(count)) {
//console.log(count); // this line only for testing
letter = text[i + 1];
letters = letter.repeat(count-1);
//console.log(letters);
result += letters;
//console.log(result); // this line only for testing
} else {
result += text[i];
}
}
return result;
}
console.log(decode("v2rt3b2xz3f2d 2s2 j"));
vrrtbbbxxzfffdd ss j

最佳答案

typeof Number(x) 将始终是 'number' 无论 x 是什么。您实际上是在将 x 转换为 'number' 类型。

因此 if 子句始终为 true 并且永远不会被跳过。

关于javascript - 用javascript写一个简单的解码函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52576402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com