You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在字符串不含"!"时返回原生字符串Symbol.iterator?

自定义字符串迭代器:不含"!"时复用原生Symbol.iterator的实现

我需要实现字符串的自定义迭代器逻辑:当字符串不包含"!"时,直接返回原生的Symbol.iterator;当包含"!"时,使用自定义的迭代逻辑。以下是我修改后的代码,请求帮忙排查问题或完善实现:

var org=String.prototype[Symbol.iterator]
Object.defineProperty(
    String.prototype,Symbol.iterator,
                {
    writable: true, configurable: true, enumerable: false,
    value:function iterator(){
      // fixed 
      if(!(this).includes("!")){
        return org.call(this);
      }
    var i, inc, done = false,str=this

    return {

    next() {

    
      do custom iterator
    
     } };
    } }
    ); 

核心问题与完善建议

你的代码逻辑框架是正确的,需要补充自定义迭代器的具体实现,并优化一些细节:

  1. 优化原生迭代器的保存
    用const替代var,避免变量被意外修改:

    const orgIterator = String.prototype[Symbol.iterator];
    
  2. 完善自定义迭代器的next方法
    自定义迭代器必须返回包含done(布尔值)和value(当前迭代值)的对象。举个例子,如果要实现跳过所有"!"字符的自定义迭代逻辑,可以这样写:

    value: function iterator() {
      if (!this.includes("!")) {
        return orgIterator.call(this);
      }
      let index = 0;
      const str = this;
      return {
        next() {
          // 跳过"!"字符
          while (index < str.length && str[index] === "!") {
            index++;
          }
          if (index >= str.length) {
            return { done: true };
          }
          return {
            done: false,
            value: str[index++]
          };
        }
      };
    }
    
  3. 避免变量提升问题
    原代码中var i, inc, done = false, str=this存在变量提升,建议用let或const声明块级作用域变量,提升代码可读性。

完整示例代码

// 保存原生迭代器
const orgIterator = String.prototype[Symbol.iterator];

// 重写字符串的Symbol.iterator
Object.defineProperty(
  String.prototype,
  Symbol.iterator,
  {
    writable: true,
    configurable: true,
    enumerable: false,
    value: function iterator() {
      // 不含"!"时返回原生迭代器
      if (!this.includes("!")) {
        return orgIterator.call(this);
      }

      // 自定义迭代逻辑:跳过所有"!"字符
      let index = 0;
      const str = this;
      return {
        next() {
          while (index < str.length && str[index] === "!") {
            index++;
          }
          if (index >= str.length) {
            return { done: true };
          }
          return {
            done: false,
            value: str[index++]
          };
        }
      };
    }
  }
);

// 测试用例
console.log([..."hello"]); // 原生迭代:["h","e","l","l","o"]
console.log([..."he!ll!o"]); // 自定义迭代:["h","e","l","l","o"]

内容的提问来源于stack exchange,提问作者Marco Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 08:13:55