我想为每个数字设置一个时间戳,然后根据其自身测试每个数字时间戳。
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/