简体   繁体   English

为什么这段代码必须使用 Math.min.apply 而不仅仅是 Math.min

[英]Why does this code excert have to use Math.min.apply rather than just Math.min

I was reading the following abbreviated code exert from this post that gets the 'minimum' date in a list of dates:我正在阅读这篇文章中的以下缩写代码,它在日期列表中获取“最小”日期:

var dates=[];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
var minDate=new Date(Math.min.apply(null,dates));

Is someone able to explain why we need to use .apply here?有人能解释为什么我们需要在这里使用.apply吗?

I understand that .apply is used to execute a function with a supplied a this value but I don't understand why the code requires the min function to be called with this=null and why the code does not work when you substitute: Math.min.apply(null, dates) for Math.min(dates)我知道.apply用于执行 function 并提供了this值,但我不明白为什么代码需要使用this=null调用min Math.min.apply(null, dates)以及为什么替换时代码不起作用: Math.min.apply(null, dates) for Math.min(dates)

It's because the Function.prototype.apply() method has two parameters.这是因为Function.prototype.apply()方法有两个参数。 First is the newly assigned this value and the second is an array of arguments that will be passed to the called function.第一个是新分配的this值,第二个是 arguments 的数组,它将传递给被调用的 function。

Your example does not do anything special with the first parameter but it does with the second.您的示例对第一个参数没有做任何特别的事情,但对第二个参数却有。

Math.min() accepts an infinite amount of arguments. Math.min()接受无限量的 arguments。 Your examples passes the array of dates as an argument and spreads the items in the array as arguments.您的示例将日期数组作为参数传递,并将数组中的项目传播为 arguments。 Nowadays you could do something like this, with the spread syntax.现在你可以用扩展语法做这样的事情。

var minDate = new Date(Math.min(...dates));

Math.min requires one or more values passed as parameters. Math.min需要一个或多个作为参数传递的值。 Since the date strings have been pushed into an array, passing an array will just use the array as a value, not the dates.由于日期字符串已被推入数组,因此传递数组只会使用数组作为值,而不是日期。

Using apply will pass the elements of the array as arguments, it's effectively the same as using spread syntax:使用apply会将数组的元素作为 arguments 传递,它实际上与使用扩展语法相同:

Math.min(...dates);

Since the first argument passed to apply is the value to use for this , and Math.apply doesn't care what this is, null is passed (you could pass any value).由于传递给apply的第一个参数是用于this的值,并且 Math.apply 不关心是什么,因此传递了null (您可以传递任何值)。

This technique was common before spread syntax was introduced in ECMAScript 2016 (ed 7).在 ECMAScript 2016(第 7 版)中引入扩展语法之前,这种技术很常见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM