Javascript
Javascript - for문 break처럼 사용하는 함수 - [ some() ]
Back
2019. 3. 21. 11:55
SOME()
1
2
3
4
5
6
|
let item;
['a','b','c','d','e'].forEach( v =>{
if(v === 'd'){
item = v;
}
});
|
cs |
배열중 'd'를 지정해서 item에 넣는 짓을 굳이 할 필요는 없지만
이런 코드가 있다면 d를 찾기 위해
배열 0부터 e 까지 반복 될 것이다.
만약 a를 찾는다고 해도 e까지 반복 될텐데
이럴경우 타언어(C, java ... )의 break를 사용하면
for문의 반복문을 빠져 나올수 있다.
break를 사용하면 for while..등은 있지만..
1
2
3
4
5
6
7
|
let item;
['a','b','c','d','e'].forEach( v =>{
if(v === 'd'){
item = v;
break;
}
});
|
cs |
이런식으로 사용 할 수 있는데
이 예제는 에러가 날 것이다.
foreach에는 break;가 없다
for,
그러면 이 방식은 some()함수를 이용하여 처리 할 수있다.
1
2
3
4
5
6
7
|
let item;
['a','b','c','d','e'].some( v =>{
if(v === 'd'){
item = v;
}
return (v === 'd');
});
|
cs |
이렇게 했을 경우 같은 조건으로
return이 true일 때 반복문을 빠져 나오기 된다.
Javascript-using a for statement like break-[some()]
SOME()
1
2
3
4
5
6
|
let item;
['a','b','c','d','e'].forEach( v =>{
if(v === 'd'){
item = v;
}
});
|
cs |
It is not necessary to specify'd' in the array and put it in the item.If you have code like this, to find dArrays 0 through e will be repeated.
Even if I find a, it will repeat until e In this case, if you use breaks in other languages (C, java ...) You can exit the loop of the for statement.
With break
1
2
3
4
5
6
7
|
let item;
['a','b','c','d','e'].forEach( v =>{
if(v === 'd'){
item = v;
break;
}
});
|
cs |
This example will give you an error.
javascript
break;
for for statement (while, forEeach .... ) ; There is no function.
Then this method can be handled using the some() function.
1
2
3
4
5
6
7
|
let item;
['a','b','c','d','e'].some( v =>{
if(v === 'd'){
item = v;
}
return (v === 'd');
});
|
cs |
In this case, under the same conditions When return is true, the loop is exited.
Javascript - for文breakのように使用する - [some()]
SOME()
1
2
3
4
5
6
|
let item;
['a','b','c','d','e'].forEach( v =>{
if(v === 'd'){
item = v;
}
});
|
cs |
もしaを探していたとしてもeまでを繰り返しなるはずだ この場合、他の言語(C、java ...)のbreakを使用すると、 for文のループを抜け出るている。
breakを使用すると、
1
2
3
4
5
6
7
|
let item;
['a','b','c','d','e'].forEach( v =>{
if(v === 'd'){
item = v;
break;
}
});
|
cs |
この例では、エラーが出るだろう。
break;
機能がない。
これにより、この方法は、some()関数を使用して処理することができる。
1
2
3
4
5
6
7
|
let item;
['a','b','c','d','e'].some( v =>{
if(v === 'd'){
item = v;
}
return (v === 'd');
});
|
cs |