我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
当前回答
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
var keepGoing = true;
ary.forEach(function(value, index, _ary) {
console.log(index)
keepGoing = true;
ary.forEach(function(value, index, _ary) {
if(keepGoing){
if(index==2){
keepGoing=false;
}
else{
console.log(value)
}
}
});
});
其他回答
使用Array Some方法
var exists = [0,1,2].some(function(count){
return count == 1
});
Exists将返回true,您可以将其用作函数中的变量
if(exists){
console.log('this is true!')
}
数组一些方法- Javascript
onSelectionChanged(event) {
let selectdata = event['api']['immutableService']['gridOptionsWrapper']['gridOptions']['rowData'];
let selected_flag = 0;
selectdata.forEach(data => {
if (data.selected == true) {
selected_flag = 1;
}
});
if (selected_flag == 1) {
this.showForms = true;
} else {
this.showForms = false;
}
}
我更喜欢用return来做。将循环部分放在私有函数中,并在想要打破循环时返回。
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
var keepGoing = true;
ary.forEach(function(value, index, _ary) {
console.log(index)
keepGoing = true;
ary.forEach(function(value, index, _ary) {
if(keepGoing){
if(index==2){
keepGoing=false;
}
else{
console.log(value)
}
}
});
});
你可以用这个:
var count = 0;
var arr = [0,1,2];
for(var i in arr){
if(count == 1) break;
//console.log(arr[i]);
}