I have the following function
function min() {
var array = Array.prototype.slice.call(arguments);
array = array.length === 1 && isNumeric(array[0].length) ? array[0] : array;
var min = array[0];
var i, count;
for (i = 1, count = array.length; i < count; i++) {
if (array[i] < min) min = array[i];
}
return min;
},
I don't understand why the following line was placed in, what is its purpose?
array = array.length === 1 && isNumeric(array[0].length) ? array[0] : array;
condition ? returnIfTrue : returnIfFalse
condition ? returnIfTrue : returnIfFalse
is called a ternary operator. array.length === 1 && isNumeric(array[0].length)
means "If array
has a single element and that first element is itself an Array". a = ternaryOperator
means set a
to the result of the ternary operator. These three together mean that you can call min
in two ways:
min(1, 2, 3)
or min([1, 2, 3])
.
That line allows passing numbers directly as arguments or passing a single array as the first argument:
min(1,2,3);
min([1,2,3]);
I would refactor this function into
var min = (...args) => Array.isArray(args[0]) ? Math.min(...args[0]) : Math.min(...args); document.write("<pre>" + min([1,2,3,4,-1]) + "</pre>"); document.write("<pre>" + min(1,2,-3,4,-1) + "</pre>");
Your code is confusing, try doing something like this
var min = 1000000;
var temp = 0;
if ( element < min){
temp = element;
min = element;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.