The problem of selecting the minimum value in the array
when selecting the minimum value in the array, it is found that there will be a problem if the code like this runs directly in < script > < / script >.
Code 1
<script>
var name=[12,3,65,8,2,12];
var min = name[0];
for (var i = 1; i <= 1; iPP) {
if (name[i]<min)
{
min = name[i];
}
}
console.log(min);
}
</script>
Code 2
<script>
function test(){
var name=[12,3,65,8,2,12];
var min = name[0];
for (var i = 1; i <= 1; iPP) {
if (name[i]<min)
{
min = name[i];
}
}
console.log(min);
}
}
test();
</script>
The result of
2 pieces of code is different. Want to know why?
this is caused by global variables. We know that window can be used directly in the < script > < / script > tag. In fact, there are many such global variables, such as
name (default is empty)
length (default is 0)
you may also wonder: why did you get 1 in the first way of writing? let's analyze your code:
<script>
var name=[12,3,65,8,2,12]; //
var min = name[0];
for (var i = 1; i <= 1; iPP) {
if (name[i]<min){
min = name[i];
}
}
console.log(min);
</script>
// namename name.toString()
// forname "12,3,65,8,2,12", 1
Let's take a look at the second paragraph of code:
function test(){
var name=[12,3,65,8,2,12]; //
var min = name[0];
for (var i = 1; i <= 1; iPP) {
if (name[i]<min)
{
min = name[i];
}
}
console.log(min);
}
test();
// namefor:[12,3,65,8,2,12] 12 < 33
Summary: when defining variables, is best not to use name, because globally name will be converted to a string . Length can be used, remember that there are other global variables, if you are interested, search it yourself.
like it if it helps!
you can try this method: `const arr = [1, 2, 3, 4, 5, 6];
min = 100;
for (var i = 0; I
if (arr[i] < min) {
min = arr[i];
}
}
console.log (min, "this is the result you want"); `
window.name
var arr=[1,2,3]
var min = Math.min(..arr)
console.log(min)
all the above answers are correct, and I tried it on the console
window.name is modified once unless the page is closed and reopened, it will always be modified. Oh, not even refreshing.
var arr = [12,3,65,8,2,12];
function test(arr){
return Math.min.apply(Math,arr);
}
test(arr);
it feels a little easier this way