我有一个数组
var myArray = [5,8,1,4,2,9,3,7,6];
我希望输出为[ 9, 1, 8, 2, 7, 3, 6, 4, 5 ]
。我尝试了以下代码:
function firstAndLast(array) {
var arr= [];
array = myArray.sort().reverse();
for(var i = 0; i < array.length; i++){
var firstItem = myArray[i];
var lastItem = myArray[myArray.length - 1];
if(lastItem > firstItem){
arr.push(array[i]);
}}
var display = firstAndLast(myArray);
console.log(display);
有人能建议我为实现目标结果而想念的东西吗?
我要实现的目标是将数组排列在偶数奇数索引中,其中奇数索引包含降序的较大值,偶数索引包含升序的值
答案 0 :(得分:1)
您的代码实际上符合您的描述,但以下部分除外:
if(lastItem > firstItem){
arr.push(array[i]);
}
为什么不将两个项目都推送到数组中?
if(lastItem > firstItem){
arr.push(firstItem, lastItem);
}
并且lastItem
应该依赖于i
:
var lastItem = array[array.length - i - 1];
他们只需要
return arr;
最后应该可以工作了:)
function firstAndLast(array) {
const result = [];
array = array.sort((a, b) => a - b).reverse();
for(var i = 0; i < array.length; i++){
var firstItem = array[i];
var lastItem = array[array.length - i - 1];
if(lastItem < firstItem){
result.push(firstItem, lastItem);
}
}
return result;
}
var myArray = [5,8,1,4,2,9,3,7,6];
console.log(firstAndLast(myArray));
现在,这仅省略了中间的值,您可以在循环中轻松添加如下值:
if(firstItem === lastItem) {
result.push(firstItem);
}
答案 1 :(得分:0)
您显然要对数组进行随机播放吗?
如果是这种情况,最简单的方法就是使用它
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
这是费舍尔·耶茨的洗牌。
有关链接的更多信息:https://bost.ocks.org/mike/shuffle/
如果不是这种情况,请发表评论回复,以便我们找到一些新的排序逻辑!
答案 2 :(得分:0)
function firstAndLast(array) { //You're declaring array here but you're using it in line 3 using the same array without, you're pasing myArray in line 12, my sugestion is to declare array inside de function
var arr = [];
array = myArray.sort().reverse();
for(var i = 0; i < array.length; i++) {
var firstItem = myArray[i];
var lastItem = myArray[myArray.length - 1]; //You're always using the last item of your array, if i'm not wrong (or confused) you want decrement the position, right? you have to use myArray.length-i or a new variable to decrement the position
if(lastItem > firstItem)
arr.push(array[i]); //Again, you're using array when you want to use myArray (it is what you're using for the position in line 5 and 6)
}
var display = firstAndLast(myArray);
console.log(display);