这是交易.我正在做一些字符串操作,我经常使用substr方法.但是,我需要使用它的方式更像是一个php fread方法.然而,我的substr需要由指针引导.这个过程需要像这样:
var string='Loremipsumdolorsitamet,consectetur'
Run Code Online (Sandbox Code Playgroud)
如果我读了,'Lorem'.....作为我的第一个子调用:
string.substr(offset,strLenth)//0,5
Run Code Online (Sandbox Code Playgroud)
那么我的下一个substr调用应该自动从我的字符串中的这个位置开始的偏移量开始:
offset pointer starts here now=>ipsumdolorsitamet,consectetur'
Run Code Online (Sandbox Code Playgroud)
如果您没有注意到,偏移量需要知道,从字符串中的第六个位置开始.
Soooo ......我想出了这个有效的解决方案,我想知道它是否是一个好的解决方案,或者是否有人有任何建议添加到它?
var _offSetPointer=0
var _substrTest={
_offset:function(){return _offSetPointer+=getLength}
};
//usage, where p is the length in bytes of the substring you want to capture.
string.substr(_substrTest._offset(getLength=p),p)
Run Code Online (Sandbox Code Playgroud)
Cri*_*hez 10
var reader = function (string, offset) {
offset = offset || 0;
return function (n) {
return string.substring(offset, (offset+=n||1));
}
}
var read = reader("1234567");
read(2)
"12"
read(3)
"345"
read()
"6"
read(1)
"7"
Run Code Online (Sandbox Code Playgroud)