我对javascript还是很陌生,我通过做一个项目来学习。 我有一个情景,可以将各种任务的状态收集到一个数组中。
var statuses = ["deployed", "deployed", "pending", "staged"];
现在,当clearInterval(interval)
中的所有项目均为array
时,我想致电deployed
答案 0 :(得分:2)
var statuses = ["deployed", "deployed", "pending", "staged"];
if(statuses.every(x=>x === "deployed")){
//clearInterval(interval);
}
console.log(statuses.every(x=>x === "deployed"))
您可以使用every
来检查数组中的所有元素是否都是deployed
。上面的代码仅基于您的描述当阵列中的所有项目均已部署时,我想调用clearInterval(interval)
答案 1 :(得分:1)
使用every
方法:
if (statuses.every(status => status === "deployed")) {
clearInterval(interval);
}
答案 2 :(得分:0)
所以这是我认为您应该做的,并且效果很好。病会分解一切,这样才有意义。
/// I just dont like using strings when ints will suffice, so im using 0,1,2 instead of your defined strings.
var valueRef = { 0: "Deployed", 1: "Pending", 2: "Staged" };
/// Info contains your sample data.
var info = [0,0,1,2]
/// This will be needed to clear the repeating fn call
var timeoutKey;
function checkIfAllDeployed(){
/// Get the size of your info array
var len = info.length;
for (index in info){
/// Loop through all items in the array to check to see if they are 0 (deployed)
if (info[index] == 0){
/// it is 0, subtract 1.
len --;
}
}
/// since you have the length (this sample is 4), when the function finally runs and they are all deployed, then len will now be 0 here.
if (len <= 0){
/// Turn off the timeout.
clearTimeout(timeoutKey);
}
/// I use bind so that what the scope is the same as the parent, so it has access to timeoutKey
}.bind(this);
/// Sets your timeout. This is where you kick it all off at. It will run at an interval of whatever you want. 1000 == 1 second. So 500 = 0.5 seconds.
timeoutKey = setInterval(checkIfAllDeployed, 500)
现在,它涵盖了循环,但是由于您正在使用ES6,因此有一些很酷的技巧,例如数组的every
函数。需要一个函数进行比较。
var timeoutKey
function checkIfAllDeployed(){
if (info.every(function(item){ return item == 0}){
clearTimeout(timeoutKey)
}
}
setInterval(checkIfAllDeployed, 500);
或者如果您想使用速记:
var timeoutKey
function checkIfAllDeployed(){
/// Now in my example, i use 0, but you can use the string "deployed" here.
if (info.every(x => x == 0){
clearTimeout(timeoutKey)
}
}
setInterval(checkIfAllDeployed, 500);
现在我使用INTS等的原因是它占用的空间更少。字符串少得多。想象一下一个巨大的字符串数组。不太好,但是有了地图,您可以轻松地重新引用。
如果您确定给定行的每个需求数据,您都可以说:
valueRef[info[index]]
,它将为您提供所需的字符串。这有点像枚举,如果需要,也可以使用。由于您具有一组静态状态,因此您只需创建一个枚举即可,它的工作方式类似于我给您的地图示例。
答案 3 :(得分:0)
遍历“状态”,检查每个当前值是否为“未部署”。第一次满足条件时,您就知道不需要执行“ clearInterval”逻辑。这意味着,如果永不满足该条件,则可以继续执行该逻辑。
答案 4 :(得分:0)
Ciasto!
据我所知,您只是试图遍历statuses数组并验证该数组的每个元素仅包含字符串“ deployed”。下面的代码是该代码的一个简单实现,我插入了一些控制台日志语句来帮助说明逐步执行该过程的逻辑。
function isDeployed(array) {
for (var i = 0; i < statuses.length; i++) {
if (statuses[i] !== 'deployed') {
return false;
}
}
return true;
}
var statuses = ["deployed", "deployed", "pending", "staged"];
// var statuses = ["deployed", "deployed", "deployed", "deployed"];
var result = isDeployed(statuses);
console.log(result);
if (result) {
console.log('Add more code to deal with your next steps');
}
让我知道您是否需要进一步澄清,或者这与您的要求不完全相同!