打字稿循环遍历带有索引和值的字符串

Fel*_*els 10 typescript

我想遍历一个字符串,我想在这个索引处同时拥有索引和字符。我知道我可以为此使用一个简单的 for 循环,但我认为 Javascript/Typescript 的一些新功能可能更优雅,所以我尝试了这个:

for (const [i, character] of Object.entries('Hello Stackoverflow')) {
    console.log(i);
    console.log(typeof(i));
    console.log(character);
}
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,这有效,但是即使i计数,它也是一个字符串。因此,例如这不起作用:

'other string'.charAt(i)
Run Code Online (Sandbox Code Playgroud)

我是 Typescript 的新手,所以我的问题是:

  • 为什么 ia 是字符串而不是数字?
  • 有没有更简单/更优雅的方法来做到这一点?

zer*_*kms 16

Unicode 安全的方法是使用扩展语法拆分为字符:

const chars = [...text];
Run Code Online (Sandbox Code Playgroud)

然后你使用good old进行迭代 Array.prototype.forEach

chars.forEach((c, i) => console.log(c, i));
Run Code Online (Sandbox Code Playgroud)


小智 5

为什么 ia 是字符串而不是数字?

因为Object.entries()返回一个键值对并且旨在用于对象,其中键当然是字符串。

有没有更简单/更优雅的方法来做到这一点?

只需一个简单的 for 循环charAt(i)即可解决问题:

const text = 'Hello StackOverflow';
for (let i = 0; i < text.length; i++) {
  const character = text.charAt(i);
  console.log(i, character);
}
Run Code Online (Sandbox Code Playgroud)