자바 스크립트의 array.select () 있습니까? array.select {|x| x > 3} 다음과

자바 스크립트는 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 언어에서는 지원되지 않을 수 있습니다.

2020 년 11 월 업데이트 : 이제 모든 주요 브라우저에서 Array.filter가 지원됩니다 .


답변

Underscore.js는 이러한 종류의 작업에 적합한 라이브러리입니다. 가능한 경우 Array.filter와 같은 내장 루틴을 사용하고 그렇지 않은 경우 자체 루틴을 사용합니다.

http://documentcloud.github.com/underscore/

문서는 사용에 대한 아이디어를 제공 할 것입니다. 자바 스크립트 람다 구문은 루비 나 다른 것만 큼 간결하지 않으며 (예를 들어 항상 명시적인 return 문을 추가하는 것을 잊어 버림) 범위는 잡을 수있는 또 다른 쉬운 방법입니다. 게으른 목록 이해와 같은 구조를 제외하고는 대부분의 작업이 매우 쉽습니다.

.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.find()찾은 첫 번째 일치 요소를 반환하는 ES6 에도 있습니다 .

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

답변

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;
  };
}

자세한 내용 은
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter 를 참조하십시오.