[ 자바스크립트 ] 배열에서의 some() 사용법 🕔 2016. 11. 5. 07:19
Use the Google Translate, if you want to read this page in your language.
But its translation is probably inaccurate.
☞ Go to the Google Translate.
[ Javascript ] some() of the array
Polyfill
<script type="text/javascript">
/*
* source :
* https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/some
*/
if ( ! Array.prototype.some ){
Array.prototype.some = function some ( func , toBeThis ){
if ( this == null || typeof func !== "function" ){
var message = ( this == null ) ? "Array.prototype.some called on null or undefined" :
"First argument must be a function.";
throw new TypeError( message );
}
var obj = Object( this );
var length = obj.length >>> 0;
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for ( var i = 0; i < length; i++ ){
if ( i in obj && func.call(thisArg, obj[i], i, obj) ){
return true;
}
}
return false;
};
}
</script>
또는, ( Another way is below. )
<script type="text/javascript">
// source : https://tonks.tistory.com/170#_javascript_array_some
if ( ! Array.prototype.some ){
Array.prototype.some = function some ( func , toBeThis ){
if ( this == null || typeof func !== "function" ){
var message = ( this == null ) ? "Array.prototype.some called on null or undefined." :
"First argument must be a function.";
try { throw new Error( message ); }
catch( error ) {
error.name = "TypeError";
throw error;
}
}
var thisArg = arguments.length > 1 ? toBeThis : undefined;
var obj = Object( this );
var length = obj.length >>> 0;
var isString = false;
var x;
if ( Object.prototype.toString.call( obj ) == "[object String]" ){
isString = true;
}
for ( x = 0; x < length; x++ ){
if ( x in obj ){
if ( isString && obj[ x ] == undefined ){ obj[ x ] = this.charAt( x ); }
if ( func.call( thisArg, obj[x], x, obj ) ){ return true; }
}
}
return false;
};
}
</script>
some() :
내가 설정한 조건에 맞아떨어지는 것이 배열 안에 들어있는지를 확인할 수 있다.
When you have set the condition in the function,
you can check whether a item matching that condition is in array.
Example 1
10 글자가 넘어가는 단어가 하나라도 있는가? ( Is there at least one string that contain more than 10 characters? )
<button onclick="testing()"> Click me </button>
<p id="demo"> </p>
<script type="text/javascript">
var maximum = 10;
function isExceeded ( value ) { return ( "" + value ).length > maximum; }
function testing (){
var names = [ "Sirius", "Tonks", "NearlyHeadlessNick", "Luna" ];
var check = names.some( isExceeded );
demo.innerHTML = check;
}
</script>
Example 2
홀수가 단 한 개라도 들어있는가? ( Is there contained at least one odd number in array? )
아래의 세 예문은, 홀수가 있는지 없는지를 확인하는 방법이다.
In three examples below, it checks whether an odd number exists.
<button onclick="testing()"> Click me </button>
<p id="demo"> </p>
<script type="text/javascript">
function testing (){
var numbers = [ -8, -2, 3, 6 ];
var check = numbers.some( function ( value ){ return !isNaN( value ) && Math.abs( value ) % 2 === 1; } );
demo.innerHTML = check;
}
</script>
<button onclick="testing()"> Click me </button>
<p id="demo"> </p>
<script type="text/javascript">
function isOdd ( value ) { return !isNaN( value ) && Math.abs( value ) % 2 === 1; }
function testing (){
var numbers = [ -8, -2, 3, 6 ];
var check = numbers.some( isOdd );
demo.innerHTML = check;
}
</script>
<button onclick="testing()"> Click me </button>
<p id="demo"> </p>
<script type="text/javascript">
function testing (){
var numbers = [ -8, -2, 3, 6 ];
var check = false;
for ( var x = 0; x < numbers.length; x++ ){
var value = numbers[ x ];
check = !isNaN( value ) && Math.abs( value ) % 2 === 1;
if ( check ){ break; }
}
demo.innerHTML = check;
}
</script>
Example 3
허용된 범위를 벗어나는 숫자가 있는가?
Is there a number that is outside the allowable range?
<button onclick="testing()"> Click me </button> <p id="demo1"> </p> <p id="demo2"> </p> <script type="text/javascript"> var range = { minimum: 10, maximum: 20 }; var array_1 = [ 2, 14, 16 ]; var array_2 = [ 12, 14, 16 ]; function testing (){ var result1 = checking( array_1 ); var result2 = checking( array_2 ); demo1.innerHTML = result1; demo2.innerHTML = result2; } function checking ( array ){ var isOutsideRange = function ( value ){ return !isNaN( value ) && ( value < range.minimum || value > range.maximum ); }; var check = array.some( isOutsideRange ); var text = "<br />"; if ( check ){ text += "예, 범위를 벗어난 숫자가 하나 이상 있습니다. <br />"; text += "Yes, numbers that are outside the range, are one or more. <br />"; } else { text += "아니오, 모든 숫자가 범위 안에 들어갑니다. <br />"; text += "No, all numbers are within the allowed range. <br />"; } return text; } </script>
Example 4
최고 기록을 세웠는가? Is that the best record?
<button onclick="testing1()"> Click me </button>
<p id="demo1"> </p>
<script type="text/javascript">
var scores = [ 5, 8, 10, 3 ];
function testing1 (){
var current = 7;
var higherThanCurrent =
function ( score ){ return score > current; };
var text = "<br />";
if ( scores.some(higherThanCurrent) ){
text += "이런, 다시 해보세요! <br />";
text += "Oops, try again! ";
}
else {
text += "축하합니다! 최고 기록을 세우셨네요. <br />";
text += "Congratulations, you've got the best record! ";
}
demo1.innerHTML = text + "<br />";
}
</script>
|
<button onclick="testing2()"> Click me </button>
<p id="demo2"> </p>
<script type="text/javascript">
var scores = [ 5, 8, 10, 3 ];
function testing2 (){
var current = 10;
var higherThanCurrent =
function ( score ){ return score > current; };
var text = "<br />";
if ( scores.some(higherThanCurrent) ){
text += "이런, 다시 해보세요! <br />";
text += "Oops, try again! ";
}
else {
text += "축하합니다! 최고 기록을 세우셨네요. <br />";
text += "Congratulations, you've got the best record! ";
}
demo2.innerHTML = text + "<br />";
}
</script>
|
또는 ( Or, )
<button onclick="testing1()"> Click me </button>
<p id="demo1"> </p>
<script type="text/javascript">
var scores = [ 5, 8, 10, 3 ];
function higherThanCurrent ( score ){
return score > this;
}
function testing1 (){
var current = 7;
var result = scores.some( higherThanCurrent, current );
var text = "<br />";
if ( result ){
text += "이런, 다시 해보세요! <br />";
text += "Oops, try again! ";
}
else {
text += "축하합니다! 최고 기록을 세우셨네요. <br />";
text += "Congratulations, you've got the best record! ";
}
demo1.innerHTML = text + "<br />";
}
</script>
|
<button onclick="testing2()"> Click me </button>
<p id="demo2"> </p>
<script type="text/javascript">
var scores = [ 5, 8, 10, 3 ];
function higherThanCurrent ( score ){
return score > this;
}
function testing2 (){
var current = 10;
var result = scores.some( higherThanCurrent, current );
var text = "<br />";
if ( result ){
text += "이런, 다시 해보세요! <br />";
text += "Oops, try again! ";
}
else {
text += "축하합니다! 최고 기록을 세우셨네요. <br />";
text += "Congratulations, you've got the best record! ";
}
demo2.innerHTML = text + "<br />";
}
</script>
|
Example 5
some() 함수가 return시키는 값은 언제나 true 아니면 false 이다.
"some()" function always returns true or false.
<button onclick="testing1()"> Click me </button>
<p id="demo1"> </p>
<script type="text/javascript">
var scores = [ 5, 8, 10, 3 ];
function testing1 (){
var current = 7;
var text = scores.some( higherThanCurrent, current );
demo1.innerHTML = text;
}
function higherThanCurrent ( score ){
var text = "<br />";
if ( score > this ){
text += "이런, 다시 해보세요! <br />";
text += "Oops, try again! ";
}
else {
text += "축하합니다! 최고 기록을 세우셨네요. <br />";
text += "Congratulations, you've got the best record! ";
}
return text + "<br />";
}
</script>
|
<button onclick="testing2()"> Click me </button>
<p id="demo2"> </p>
<script type="text/javascript">
var scores = [ 5, 8, 10, 3 ];
function testing2 (){
var current = 10;
var text = scores.some( higherThanCurrent, current );
demo2.innerHTML = text;
}
function higherThanCurrent ( score ){
var text = "<br />";
if ( score > this ){
text += "이런, 다시 해보세요! <br />";
text += "Oops, try again! ";
}
else {
text += "축하합니다! 최고 기록을 세우셨네요. <br />";
text += "Congratulations, you've got the best record! ";
}
return text + "<br />";
}
</script>
|
Example 6
배열 안에서, 원하는 위치까지만 실행하기.
Execute until the desired index in array.
<button onclick="testing()"> Click me </button>
<p>세번째 숫자까지만 더하시오. Add until the third number. </p>
<p id="numbers"> 6, 13, 25, 37, 40 </p>
<p id="demo"> </p>
<script type="text/javascript">
var numbers = [ 6, 13, 25, 37, 40 ];
var sum = 0;
function example ( num, index ){
sum += num;
return index > 2;
}
function testing (){
numbers.some( example );
demo.innerHTML = sum;
}
</script>
return시킬 값을 설정하지 않으면, some()의 괄호 안에 넣어준 함수는
그 배열의 끝까지 계속해서 실행된다.
If the return value is not defined,
a function for inputting in brackets of "some()" method, is run repeatedly until last value in array.
<button onclick="testing()"> Click me </button> <p id="demo"> </p> <script type="text/javascript"> var numbers = [ 6, 13, 25, 37, 40 ]; var sum = 0; function sumTotal ( num ){ // ← 이 함수에는 리턴값이 없음!! ( This function has no return value!! ) sum += num; } function testing (){ numbers.some( sumTotal ); demo.innerHTML = sum; } </script>
이 내용이 도움이 되셨다면, 아래의 하트 버튼을 눌러주세요. *^^*
If this article is helpful to you, please click the heart button below. *^^*
'JAVASCRIPT > Array' 카테고리의 다른 글
[ 자바스크립트 ] 배열의 slice() 사용법 (0) | 2017.05.01 |
---|---|
[ 자바스크립트 ] Array.isArray() (0) | 2017.05.01 |
[ 자바스크립트 ] 배열에서의 every() 사용법 (0) | 2016.10.30 |
[ 자바스크립트 ] 배열의 sort()에 대해 알아보기 (3) | 2016.01.20 |
[ 자바스크립트 ] 배열에서 lastIndexOf() 사용하기 (0) | 2016.01.08 |