JavaScript 배열 filter() 메소드는 제공된 함수에 의해 구현된 테스트를 통과하는 모든 요소로 새 배열을 생성합니다.
다음은 매개변수입니다 -
-
콜백 − 배열의 각 요소를 테스트하는 함수입니다.
-
이 개체 − 콜백 실행 시 사용할 객체입니다.
JavaScript에서 filter() 메서드로 작업하는 방법을 배우기 위해 다음 코드를 실행할 수 있습니다 -
예시
<html>
<head>
<title>JavaScript Array filter Method</title>
</head>
<body>
<script>
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
document.write("Filtered Value : " + filtered );
</script>
</body>
</html>