使用JavaScript中的for each函数比较数组中的值

Comparing values in an array using a for each function in JavaScript

本文关键字:数组 比较 函数 JavaScript 中的 for each 使用      更新时间:2023-11-25

我有一个任务,使用for each函数在数组上执行一些特定任务。除了最后一个,我的所有东西都在工作——我很接近,但返回的第一个和最后一个值都不正确。

在isNextGreater函数中,我需要获取数组中某个元素的值,并将其与下一个元素进行比较。如果元素的值是<下一个元素的值我需要返回一个-1。如果值更大,我需要返回1。最后一个元素需要返回其原始值,因为没有什么可比较的。

当函数运行时,它返回[1]和[2]的正确值,但[0]返回其原始值,[3]返回1。

我知道我离得很近,但缺少什么!有人能告诉我我在看什么吗?

谢谢!

<!doctype html>
<html>
<head>
<title> Functions: forEach </title>
<meta charset="utf-8">
<script>
// the zeros array
var zeros = [0, 0, 0, 0];
// your code here
//Function to display the contents of the Array.
function showArray (value, index, theArray) {
console.log("Array[" + index + "]" + ":" + value);
}  
//Function to assign random values to the passed array
function makeArrayRandom(value, index, theArray) {
var maxSize = 5;
var randomNum = Math.floor(Math.random() * maxSize);
theArray[index] = randomNum;
console.log("Array[" + index + "]" + ":" + randomNum);    
}
//Function to create a copy of the random numbers array
function map(value, index, theArray) {
var arrayCopy = [];      
arrayCopy[index] = theArray[index];
console.log("Array[" + index + "]" + ":" + value); 
return arrayCopy;
}
//Function to compare the values of the array
function isNextGreater(value, index, theArray) {  
var size = theArray.length  
for (var i = 0; i < size; i++) {            
if (theArray[i] < theArray[i+1]){
   theArray[i] = -1;
} else {
   theArray[i] = 1;
}  
}
console.log("Array[" + index + "]" + ":" + value);            
} 
//Use ForEach to pass Array data to functions.                          
console.log("Display the Array:");
zeros.forEach(showArray);
console.log("Random Array:");
zeros.forEach(makeArrayRandom);
console.log("Copy of Zeros:");
zeros.forEach(map);
console.log("Is Next Greater:");
zeros.forEach(isNextGreater);
</script>
</head>
<body>
</body>

isNextGreater函数更改为此函数,就完成了。

function isNextGreater(value, index, theArray) {  
    var size = theArray.length  
    if (index < size - 1){
        if (value < theArray[index+1] ){
            value = -1;
        } else {
            value = 1;
        }  
    }else{
        value = value;
    }
    console.log("Array[" + index + "]" + ":" + value);            
} 

这里有一个小提琴来检查结果(结果显示在控制台上)