小编yet*_*ker的帖子

运行指定次数的函数

function runAgain()
{
    window.setTimeout(foo, 100);
}

function foo()
{
    //Do somthing
    runAgain();
}
Run Code Online (Sandbox Code Playgroud)

我可以使用上面的代码以一秒的间隔无限次地运行一个函数.

运行函数定义次数的标准方法是什么.让我们说,我希望foo()以1秒的间隔运行5次.

编辑据说在Javascript中应该避免使用全局变量.有没有更好的方法?

通过答案输入,我创建了一个这样的函数:(工作示例:http://jsbin.com/upasem/edit#javascript,html)

var foo = function() {
    console.log(new Date().getTime());  
};


var handler = function(count) {
    var caller = arguments.callee;
    //Infinite
    if (count == -1) {
        window.setTimeout(function() {
            foo();
            caller(count);
        }, 1000);
    }
    if (count > 0) {
        if (count == 0) return;
        foo();
        window.setTimeout(function() {
            caller(count - 1);
        }, 100);    
    }
    if (count == null) {foo(); }
}; …
Run Code Online (Sandbox Code Playgroud)

javascript

8
推荐指数
2
解决办法
2万
查看次数

找到斐波纳契数列中偶数项的总和

#!/usr/bin/python2

"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""

odd, even = 0,1
total = 0
while True:
    odd = odd + even  #Odd
    even = …
Run Code Online (Sandbox Code Playgroud)

python sum fibonacci

6
推荐指数
1
解决办法
5万
查看次数

如何在不使用c中的free()的情况下释放内存

int main(void)
{
    int *a = malloc(10);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如何在不使用的情况下释放内存free()

c

0
推荐指数
1
解决办法
1679
查看次数

相同的正则表达式在Java和Python中有不同的结果

Java代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExpTest {
    public static void main(String[] args) {

        String str = "X-Value = -0.525108, Y-Value = 7.746691, Z-Value = 5.863008, Timestamp(milliseconds) = 23001";
        String p = "Value = (.*?), ";
        Pattern pattern = Pattern.compile(p);
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()){
             System.out.println(matcher.group(1));
             System.out.println(matcher.group(2));
             System.out.println(matcher.group(3));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Java代码的输出:

$ java RegExpTest 
-0.525108
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 2
        at java.util.regex.Matcher.group(Matcher.java:487)
        at RegExpTest.main(RegExpTest.java:15)
$ 
Run Code Online (Sandbox Code Playgroud)

Python代码(在Interpreter中):

>>> import re
>>> re.findall("Value = (.*?), ", …
Run Code Online (Sandbox Code Playgroud)

python java regex

0
推荐指数
1
解决办法
1728
查看次数

标签 统计

python ×2

c ×1

fibonacci ×1

java ×1

javascript ×1

regex ×1

sum ×1