javascript - 如何使用javascript为数组中的每个项目设置唯一变量?

标签 javascript arrays variables

我想为每个数字设置一个时间戳,然后根据其自身测试每个数字时间戳。

        var timestamp;
        nums=["1", "2", "3"];
        nums2=nums.map(myFunction);


        function myFunction(num) {

          setInterval(function() {

            var current_time = Math.floor(Date.now() / 1000);

            if (typeof timestamp !== "undefined" ) {
                if (current_time > (timestamp + 60)) {
                    timestamp = Math.floor(Date.now() / 1000);
                    console.log('time stamp reset');
                } else {
                    console.log('time stamp too young will reset after 60 sec');
                }
            } else {
                timestamp = Math.floor(Date.now() / 1000);
                console.log('time stamp set');
            }

         }, 10000);

        }

****如果我运行脚本 20 秒:****

当前输出:

time stamp set

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

*(10 seconds later)*

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

所需输出:

time stamp set

time stamp set

time stamp set

*(10 seconds later)*

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

最佳答案

我不明白你在这里想做什么,所以我的答案纯粹基于你的当前输出所需输出

您的 timestamp 变量是在 global 范围内声明的,因此第一次调用 myFunction 时,它的值为 undefined,但在后续调用中它将保留一些值,从而产生“当前输出”。

要修复此问题,请将 timestamp 变量移至 myFunction 内。

nums=["1", "2", "3"];
nums2=nums.map(myFunction);


function myFunction(num) {
  var timestamp;

  setInterval(function() {

    var current_time = Math.floor(Date.now() / 1000);

    if (typeof timestamp !== "undefined" ) {
        if (current_time > (timestamp + 60)) {
            timestamp = Math.floor(Date.now() / 1000);
            console.log('time stamp reset');
        } else {
            console.log('time stamp too young will reset after 60 sec');
        }
    } else {
        timestamp = Math.floor(Date.now() / 1000);
        console.log('time stamp set');
    }

 }, 10000);

}

关于javascript - 如何使用javascript为数组中的每个项目设置唯一变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54119300/

相关文章:

javascript - .property() 的作用是什么?在函数(){}.property()中

javascript - HTML 输入字段,记住光标位置

python - 根据与列表的精确匹配返回单个 True/False 值

java - 一个只有 "private final static"变量的 java 类。这是个好主意吗?

ruby - 如何在txt文件中存储变量: Ruby

Bash 参数引号和 eval

javascript - 迭代 HTML 页面中的所有脚本标记以查找正则表达式的匹配项

javascript - 使用 XMLHttpRequest、PDO、JSON、PHP 和 JavaScript 从数据库中获取数据

java - 我如何知道 Hibernate .list() 方法中的返回值是数组还是标量?

c - C 中的大数组初始化问题