使用JavaScript中的for each函数比较数组中的值
Comparing values in an array using a for each function in JavaScript
我有一个任务,使用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);
}
这里有一个小提琴来检查结果(结果显示在控制台上)
相关文章:
- 如何使用 node.js 比较两个 json 数组
- MongoDB-通过比较集合和对象的数组来返回现有字段的数组
- underline-js:将键对象与数组键对象进行比较,如果存在,则移除现有的添加新的
- 比较二维数组js
- 如何放置ÅÄ和#214;在javascript数组中,然后将其与html文本进行比较
- 数组比较并获取计数
- Javascript数组比较问题
- 用于在数组比较之后由于某种原因而爆发循环
- javascript数组比较多次循环
- 这是有效的JavaScript数组比较算法
- 2D数组比较-嵌套循环错误
- 数组比较在Chrome工作,但不与Chrome IPAD
- 对象/数组比较算法,以确定共性/相似性
- 谷歌电子表格中的数组比较
- 整数数组比较
- Javascript数组比较
- node.js中的数组比较
- JavaScript关联数组比较
- Javascript数组比较
- JavaScript数组比较的奇怪行为