Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我正在尝试创建一个带有指针的substr方法。。。。有更优雅的解决方案吗?_Javascript - Fatal编程技术网

Javascript 我正在尝试创建一个带有指针的substr方法。。。。有更优雅的解决方案吗?

Javascript 我正在尝试创建一个带有指针的substr方法。。。。有更优雅的解决方案吗?,javascript,Javascript,事情是这样的。我正在做一些字符串操作,并且经常使用substr方法。然而,我需要使用它的方式更像是一个php-fread方法。然而,我的substr需要由指针引导。该过程需要如下操作: var string='Loremipsumdolorsitamet,consectetur' 如果我读到“Lorem”……作为我的第一个substr调用: string.substr(offset,strLenth)//0,5 然后,我的下一个substr调用将自动开始,偏移量从字符串中的这个位置开始: o

事情是这样的。我正在做一些字符串操作,并且经常使用substr方法。然而,我需要使用它的方式更像是一个php-fread方法。然而,我的substr需要由指针引导。该过程需要如下操作:

var string='Loremipsumdolorsitamet,consectetur'
如果我读到“Lorem”……作为我的第一个substr调用:

string.substr(offset,strLenth)//0,5
然后,我的下一个substr调用将自动开始,偏移量从字符串中的这个位置开始:

offset pointer starts here now=>ipsumdolorsitamet,consectetur'
如果您没有注意到,那么需要知道偏移量,从字符串中的第六个位置开始

太好了。。。我提出了这个有效的解决方案,我想知道这是否是一个好的解决方案,或者是否有人对它有任何建议

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)

+我很好,丹尼尔!是否应该用
var
定义该偏移量,并将其范围限定到该函数?@alex:谢谢!不需要使用
var
声明,因为它是作为参数引入范围的。如果你提供了偏移量,它将在调用read时从该位置开始,否则它默认为0(字符串的开头)。闭包和curry的用法很好。Daniel,请帮助我理解你的代码,因为我正在学习javascript。reader函数如何知道第一个和第二个参数是什么?如果我知道,读(7),怎么知道7不是字符串参数?@cube:当然。
reader
read
之间有区别<代码>读取器返回一个函数。当我执行
read=reader(…)
时,它将该函数分配给read变量。在Javascript中,函数维护对定义时可用的所有变量(san
this
参数
)的引用。在这种情况下,它保持对
offset
变量的访问。每次我调用
read
函数时,它都会增加这个变量。因此,下次使用
read
函数时,它将使用相同的偏移量变量(之前可能已递增)。
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"