什么返回-1以及返回0& 1 [英] What return -1 does as well as return 0 & 1

查看:135
本文介绍了什么返回-1以及返回0& 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    var library = [ 
   { author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254},
   { author: 'Steve Jobs', title: 'Walter Isaacson', libraryID: 4264},
   { author: 'Suzanne Collins', title: 'Mockingjay: The Final Book of The Hunger Games', libraryID: 3245}
   ];

function compare_to_sort(x,y) 
 {
  if (x.title < y.title)
    return -1;
  if (x.title > y.title)
    return 1;
  return 0;
 }

console.log(library.sort(compare_to_sort));





我尝试过:





What I have tried:

Write a JavaScript function to sort the following array of objects by title value.

推荐答案

想想看:当您对对象进行排序时,您需要知道a是否大于b(即b在排序顺序中排在第一位) ,或者a小于b(即a在排序顺序中排在第一位),或者如果a和b相同(即排序顺序排在第一位并不重要。)



这就是返回值的含义:

Think about it: when you sort objects, you need to know if a is bigger than b (i.e. b comes first in the sort order), or a is smaller than b (i.e. a comes first in the sort order), or if a and b are the same (i.e. it doesn't matter which comes first in the sort order.)

That's what the values returned are for:
-1 means x comes first, then y
 1 means y comes first, then x
 0 means y and x are the same

所以当你编写sort函数时,你可以使用该函数来比较相邻的元素,并且(例如)交换它们,如果它返回正值。

So when you write your sort function, you can use the function to compare adjacent elements, and (for example) swap them over if it returns a positive value.


这篇关于什么返回-1以及返回0&amp; 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆