右侧子字符串生成器

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,我们将探索 JavaScript 中生成子字符串的概念。我们将重点使用 for...in 循环和 String.prototype.slice() 方法来生成给定字符串的右侧子字符串。在本实验结束时,你将更好地理解如何在 JavaScript 中操作字符串,并为各种用例生成子字符串。

右侧子字符串生成器

要生成给定字符串的所有右侧子字符串,请执行以下步骤:

  1. 打开终端/SSH 并输入 node 以开始练习编码。
  2. 如果字符串为空,则使用 String.prototype.length 提前停止迭代。
  3. 使用 for...in 循环和 String.prototype.slice() 从末尾开始 yield 给定字符串的每个子字符串。

以下是代码片段:

const rightSubstrGenerator = function* (str) {
  if (!str.length) return;
  for (let i in str) yield str.slice(-i - 1);
};

示例用法:

[...rightSubstrGenerator("hello")];
// [ 'o', 'lo', 'llo', 'ello', 'hello' ]

总结

恭喜你!你已经完成了右侧子字符串生成器实验。你可以在 LabEx 中练习更多实验来提升你的技能。