【问题标题】:ES2015 string iterator information about indexES2015 字符串迭代器关于索引的信息
【发布时间】:2020-01-16 17:10:28
【问题描述】:

在 ES2015 或 ES6 中,字符串是可迭代的。 此功能可用于正确处理 Unicode 代理对。

例如,

const str = "a\u{1F436}b";
for (const ch of str) {
    f(ch);
}

将调用f() 3 次,而

const str = "a\u{1F436}b";
for (let i = 0; i < str.length; i++) {
    f(ch[i]);
}

将致电f() 4 次。

我想要做的是获取这些字符的开始或结束索引。 例如,对于str = "a\u{1F436}b",我想得到类似[0, 1, 3] 的内容,因为每个 unicode 字符分别从索引 0、1、3 开始。

但是,迭代器似乎没有提供有关索引的信息。

如何获取索引?

【问题讨论】:

  • 您能否详细说明这些索引将如何使用?我觉得这有点 XY 问题。
  • 你可以积累ch.length

标签: javascript string ecmascript-6 unicode


【解决方案1】:

做这样的事情怎么样

var str = "a\u{1F436}b";

let current = 0
let indexes = [...str].map(a=> {
  let temp = current
  current += a.length
  return temp
})

console.log(indexes)

String Split With Unicode

【讨论】:

    【解决方案2】:

    一种可能性是在循环中使用带有exec RegExp 方法的简单的Unicode 感知正则表达式:

    const str = "a\u{1F436}b";
    const regex = /./gu;
    let indexes = [ ];
    let match;
    while (match = regex.exec(str))
    {
        // let ch = match[0];
        indexes.push(match.index);
    }
    console.log(indexes);

    【讨论】:

      猜你喜欢
      • 2016-08-22
      • 1970-01-01
      • 2021-10-23
      • 2012-10-23
      • 2012-06-28
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多