我试图通过属性对对象数组进行排序title.这是我正在运行的代码片段,但它没有排序任何东西.数组按原样显示.PS我看了以前类似的问题.例如,这里建议并使用我正在使用的相同方法.
javascript:
function sortLibrary() {
// var library is defined, use it in your code
// use console.log(library) to output the sorted library data
console.log("inside sort");
library.sort(function(a,b){return a.title - b.title;});
console.log(library);
}
// tail starts here
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
}
];
sortLibrary();
Run Code Online (Sandbox Code Playgroud)
HTML代码:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1> Test Page </h1>
<script src="myscript.js"> </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
你试过这样的吗?它按预期工作
library.sort(function(a,b) {return (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0);} );
Run Code Online (Sandbox Code Playgroud)
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
}
];
console.log('before sorting...');
console.log(library);
library.sort(function(a,b) {return (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0);} );
console.log('after sorting...');
console.log(library);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12629 次 |
| 最近记录: |