자바 스크립트의 array.select ()
자바 스크립트는 Ruby와 비슷한 기능을 가지고 있습니까?
array.select {|x| x > 3}
다음과 같은 것 :
array.select(function(x) { if (x > 3) return true})
있습니다 Array.filter()
:
var numbers = [1, 2, 3, 4, 5];
var filtered = numbers.filter(function(x) { return x > 3; });
// As a JavaScript 1.8 expression closure
filtered = numbers.filter(function(x) x > 3);
참고 Array.filter()
인 ECMAScript 표준 아니다 , 그것은 ECMAScript를 사양 나이 ES5 이상 (감사 이순신 장쩌민과 jAndy)에 표시되지 않습니다. 따라서 MSIE에서 JScript와 같은 다른 ECMAScript 방언에서는 지원되지 않을 수 있습니다.
Underscore.js는 이러한 종류의 작업에 적합한 라이브러리입니다. 가능한 경우 Array.filter와 같은 내장 루틴을 사용하고 그렇지 않은 경우 자체 루틴을 사용합니다.
http://documentcloud.github.com/underscore/
문서는 사용에 대한 아이디어를 제공 할 것입니다. 자바 스크립트 람다 구문은 루비 나 다른 것만 큼 간결하지 않으며 (예를 들어 항상 명시적인 return 문을 추가하는 것을 잊습니다) 범위를 잡는 또 다른 쉬운 방법이지만 할 수 있습니다. lazy list comprehensions와 같은 구조를 제외하고는 대부분의 작업이 매우 쉽습니다.
.select ()에 대한 문서에서 ( .filter ()는 동일한 별칭입니다)
목록의 각 값을 살펴보고 진실 테스트 (반복자)를 통과 한 모든 값의 배열을 반환합니다. 기본 필터 메서드가있는 경우 위임합니다.
var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]
yo는 이와 같은 선택 방법으로 JS를 확장 할 수 있습니다.
Array.prototype.select = function(closure){
for(var n = 0; n < this.length; n++) {
if(closure(this[n])){
return this[n];
}
}
return null;
};
이제 이것을 사용할 수 있습니다.
var x = [1,2,3,4];
var a = x.select(function(v) {
return v == 2;
});
console.log(a);
또는 배열의 객체
var x = [{id: 1, a: true},
{id: 2, a: true},
{id: 3, a: true},
{id: 4, a: true}];
var a = x.select(function(obj) {
return obj.id = 2;
});
console.log(a);
Array.filter는 많은 브라우저에서 구현되지 않습니다. 존재하지 않는 경우이 함수를 정의하는 것이 좋습니다.
Array.prototype의 소스 코드는 MDN에 게시됩니다.
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details
There's also Array.find()
in ES6 which does the same thing as Ruby's Array.select
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
const myArray = [1, 2, 3]
const myElement = myArray.find((element) => element === 2)
console.log(myElement)
// => 2
참고URL : https://stackoverflow.com/questions/4990175/array-select-in-javascript
'Development Tip' 카테고리의 다른 글
파이썬에서 따옴표로 묶인 문자열의 구분 기호를 분할하지만 무시하는 방법은 무엇입니까? (0) | 2020.11.30 |
---|---|
DBML 디자이너에서 테이블을 빠르게 찾습니까 (검색)? (0) | 2020.11.30 |
else의 목적과 마지막으로 예외 처리 (0) | 2020.11.30 |
파이썬 셸에서 클래스를 다시로드하는 방법? (0) | 2020.11.30 |
ggplot2에 대한 미학 테이블이나 카탈로그가 있습니까? (0) | 2020.11.30 |