javascript中return 1与return 0及 return-1 有什么区别??求大神解答


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Array对象的方法</title>

<script>

var array=new Array();

//初始化数组

initArray();

      document.write("排序之前的数组为: <br/>"+array+"<br/>");

      document.write("按升序排序的数组为:<br/>"+array.sort(sortNumberAsc)+"<br/>");

      document.write("按降序排序的数组为:<br/>"+array.sort(sortNumberDesc)+"<br/>");

 document.write("按字符编码排序的数组为:<br/>"+array.sort())

 function sortNumberAsc(a,b){

 if(a<b){

 return -1;

 }

 else if(a==b){

 return 0;

 }

 else{

 return 1;

 }

 }

 function sortNumberDesc(a,b){

 if(a<b){

 return 1;

 }

 else if(a==b){

 return 0;

 }

 else{

 return -1;

 }

 }

 function initArray(){

 while(true){

 var a=prompt("请输入数值,要结束时请输入非数值数据,such as'abc' ","");

 if(isNaN(a)){

 break;

 }

 else{

 array.push(parseFloat(a));

 }

}

}


</script>

</head>


<body>

</body>

</html>





慕圣6643023
浏览 6894回答 1
1回答

千秋此意

这个是sort方法里的那个比较函数的特殊的返回值,比较函数的参数 a 和 b 代表数组里的两个元素,如果 a 小于 b,排序后的数组 a 在 b 前面,此时返回一个负数 (即上面的 return -1)如果 a 等于 b,排序后两者位置不变,此时返回 0 (即上面的 return 0)如果 a 大于 b,排序后 a 在 b 后面, 返回一个正数 (即上面的 return 1)//比较函数一般简写成: arr.sort( function(a,b){     return a-b // 升序 } ); arr.sort( function(a,b){     return b-a // 降序 } ); // 对应上面的解释好好想下,不难理解为什么这样写
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript