我刚刚开始使用javascript进行编程,我需要练习一些问题来获得带有代码构建逻辑的EXP.我得到了这个问题的功课,但由于某种原因我无法使它工作,即使它对我来说似乎是"逻辑".检查数组是使用循环降序,升序还是不分类.
我只是一个菜鸟所以请尽量帮助我解决这个问题,因为我只能在学习中循环(这是我写的代码:
var array = [1, 2, 3, 7 ];
var d = 0;
var c =0 ;
var b = 1;
var a = 0;
for (var i = 1; i <= array.length; i++)
{
if (array[c]<array[b] && a!== -1 ){
d = -1;
c =c+1;
b = b+1;
if(c==array.length){
console.log("asc");
break;
}else{
continue;
}
} else if (array[c]>array[b] && d!==-1 ){
a = -1;
d= d+1;
b = b+1;
if(i=array.length){
console.log("dsc");
break;
}else{continue;}
} else{
console.log("unsorted array");
break;
}
}
Run Code Online (Sandbox Code Playgroud)
“使用循环检查数组是否按降序、升序或未排序”
// define the array
var array = [1,2,3,7];
// keep track of things
var isDescending = true;
var isAscending = true;
// we're looking ahead; loop from the first element to one before the last element
for (var i=0, l=array.length-1; i<l; i++)
{
////////////////////////////////////////////////////////////
// log to the console to show what's happening for each loop iteration
// this is the ith iteration
console.log("loop iteration %s", i);
// breaking isDescending down:
// is this value greater than the next value?
console.log("A: (%s > %s) = %s", array[i], array[i+1], (array[i] > array[i+1]));
// have all values been descending so far?
console.log("B: isDescending: %s", isDescending);
// if this value is greater than the next and all values have been descending so far, isDescending remains true. Otherwise, it's set to false.
console.log("are A and B both true? %s", (isDescending && (array[i] > array[i+1])));
// add a line break for clarity
console.log("");
////////////////////////////////////////////////////////////
// true if this is greater than the next and all other so far have been true
isDescending = isDescending && (array[i] > array[i+1]);
// true if this is less than the next and all others so far have been true
isAscending = isAscending && (array[i] < array[i+1]);
}
if (isAscending)
{
console.log('Ascending');
}
else if (isDescending)
{
console.log('Descending');
}
else
{
console.log('Not Sorted');
}Run Code Online (Sandbox Code Playgroud)
Array.prototype.every 将其谓词传递给索引,您可以使用该索引获取元素的前任:
function isAscending(arr) {
return arr.every(function (x, i) {
return i === 0 || x >= arr[i - 1];
});
}
Run Code Online (Sandbox Code Playgroud)
在这里,我们检查每个item(x)是否大于或等于它之前的项目(arr[i - 1])或它之前没有项目(i === 0).
翻转>=到<=了isDescending.
| 归档时间: |
|
| 查看次数: |
4722 次 |
| 最近记录: |