javascript - ES2015 string iterator information about index
问题描述
In ES2015 or ES6, strings are iterable. This feature can be used to handle Unicode surrogate pairs properly.
For example,
const str = "a\u{1F436}b";
for (const ch of str) {
f(ch);
}
will call f()
3 times whereas
const str = "a\u{1F436}b";
for (let i = 0; i < str.length; i++) {
f(ch[i]);
}
will call f()
4 times.
What I want to do is getting the beginning or ending indices of those characters.
For example, for str = "a\u{1F436}b"
, I want to get something like [0, 1, 3]
because each unicode character starts at the index 0, 1, 3 respectively.
However, the iterator does not seem to give information about the index.
How can I get the indices?
解决方案
做这样的事情怎么样
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)
推荐阅读
- javascript - 为什么这段代码中的js事件没有冒泡?
- php - PHP 克隆/复制/将方法从一个对象移动到另一个对象
- swift - 二元运算符“==”不能应用于“NSObject”和“String”类型的操作数
- javascript - Firestore 数组联合
- python - 在 Python 调试器中,如何单步执行第二个方法调用?
- c# - 反序列化数组中的项目时忽略自定义 JsonConverter
- apache-nifi - Nifi:在自定义处理器中读取外部属性
- kubernetes - 没有可用于此声明的持久卷,也没有设置存储类
- authentication - 发送用户 ID 和 access_token
- javascript - 用删除重复html控件的正确方法是什么