program story

Math.max.apply ()는 어떻게 작동합니까?

inputbox 2020. 10. 26. 07:58
반응형

Math.max.apply ()는 어떻게 작동합니까?


어떻게 Math.max.apply()작동합니까?.

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <script>
      var list = ["12","23","100","34","56",
                                    "9","233"];
      console.log(Math.max.apply(Math,list));    
  </script>
</body>
</html>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

위의 코드는 목록에서 최대 수를 찾습니다. 누구든지 아래 코드가 어떻게 작동하는지 말해 줄 수 있습니까?. 통과하면 작동하는 것 같아요null or Math.

console.log(Math.max.apply(Math,list));

모두 user-defined/Native functions사용할 수있는 호출 및 적용 방법이 있습니까?.


apply배열을 받아들이고 배열을 실제 함수에 매개 변수로 적용합니다. 그래서,

Math.max.apply(Math, list);

다음과 같이 이해할 수 있습니다.

Math.max("12", "23", "100", "34", "56", "9", "233");

따라서 apply데이터 배열을 매개 변수로 함수에 전달하는 편리한 방법입니다. 생각해 내다

console.log(Math.max(list));   # NaN

max배열을 입력으로 받아들이지 않기 때문에 작동하지 않습니다.

를 사용하는 또 다른 장점은 apply자신의 컨텍스트를 선택할 수 있다는 것입니다. apply함수에 전달하는 첫 번째 매개 변수 는 해당 함수 this내부에 있습니다. 그러나 max현재 상황에 의존하지 않습니다. 따라서 모든 것이 Math.

console.log(Math.max.apply(undefined, list));   # 233
console.log(Math.max.apply(null, list));        # 233
console.log(Math.max.apply(Math, list));        # 233

apply에 실제로 정의되어Function.prototype 있으므로 유효한 JavaScript 함수 개체는 apply기본적으로 함수 를 갖습니다 .


JavaScript ES6에서는 Spread 연산자를 사용하십시오 .

var list = ["12","23","100","34","56","9","233"];
console.log(Math.max(...list));
//                   ^^^ Spread operator 

누구든지 아래 코드가 어떻게 작동하는지 말해 줄 수 있습니까?

Math.max.apply(Math,list)

함수 구현 (본문)에서 참조 로 사용하고 인수로 전달할 객체 Math.max와 함께 함수를 호출합니다 .Maththislist

그래서 이것은 결국

Math.max("12","23","100","34","56", "9","233")

null 또는 Math를 전달하면 작동하는 것 같습니다.

분명히 Math.max구현은 인스턴스 변수를 사용하지 않습니다-그렇게 할 이유가 없습니다. 기본 구현은 반복 arguments하여 최대 값을 찾습니다.

모든 사용자 정의 / 네이티브 함수에는 우리가 사용할 수있는 호출 및 적용 메소드가 있습니까?.

예, 모든 단일 기능은 call또는 사용하여 호출 할 수 있습니다.apply

참조 :


Math.max (val1, val2, ...)

Math.max(1, 2, 3); // Math.max([value1[, value2[, ...]]])
value1, value2...매개 변수이며 숫자 여야합니다. MDN Math.max

당신은 전달할 수 없습니다 arrayMath.max매개 변수를 설정합니다. 배열을 전달하려면 apply.

대다

The first parameter of apply is this, the second is array. Math methods are equivalent of static in other languages, which means it doesn't need an object instance unlike to array.prototype.slice so you don't need to pass this in this case.

Example

var arr = [1, 2, 3];

Math.max(1, 2, 3);  // -> 3
Math.max(arr);      // -> NaN (Not a Number)
Math.max.apply(null, arr);  // Math.max.apply(null, [1, 2, 3]) -> Math.max(1, 2, 3) -> 3

arr.slice(1);  // -> returns Array [2, 3]
Array.prototype.slice.call(arr, 1); // Array.prototype.slice.call([1, 2, 3], 1) == [1, 2, 3].slice(1)

When you want to pass an array as parameter you have to use apply, otherwise use call.

apply = array
call = comma separated
More about call & apply


I will start by saying Math.max(...numbers) and Function.prototype.apply() should only be used for arrays with relatively few elements. (...) and apply will either fail or return the wrong result if the array is too large

Math.max.apply(null | undefined | Math, numbers) is the same as Math.max(...numbers) so I would recommend Math.max(...numbers) for aesthetic reasons.

const numbers = [5, 6, 2, 3, 7];

const max = Math.max(...numbers);

console.log('max:', max);
// expected output: 7

const min = Math.min(...numbers);

console.log('min:', min);
// expected output: 2

If you need to find the maximum element in a numeric array that is very large: use the Array.reduce() method.

Array.reduce() can be used to find the maximum element in a numeric array, by comparing each value:

const numbers = [5, 6, 2, 3, 7];
const getMax = (numbers) => numbers.reduce((a, b) => Math.max(a, b));

const getMin = (numbers) => numbers.reduce((a, b) => Math.min(a, b));
	
const max = getMax(numbers)
const min = getMin(numbers)

console.log('max:', max)
console.log('min:', min)

Conclusion:

Numeric array that is relatively small: use Math.max(...numbers) Numeric array that is very large: use the Array.reduce() method

참고URL : https://stackoverflow.com/questions/21255138/how-does-the-math-max-apply-work

반응형