Ask 3 questions about the sort function in the JavaScript language essence book

75 4

Following code is part of the array. Sort ( comparefn ) section of the JavaScript language essence ( page81 ), but I'm using firebug to generate error messages: Missing %. After property list, message: 'expected an object when sorting by '+ name.

problem 1: the cause of error?

problem 2: assumes that the error has been modified, then it can be considered var name = 'last ', minor = by ("first"), but when the second argument? ( I might not be able to understand it, anyway, I can't understand that code, please help me to take a look at the idea of this code. )

problem 3: I & tructio & on the parameter of the anonymous function returned by the by function, which is the unde & tanding of that: Here o, p is any two parameters in the array s, and if I understand the correct rules, then this specifies how the rules for any parameter are specified, and I should? For array s, this by function calculates a few times, is it 15 times. If not, it's a few times, why.

window.onload = function () {
 var by = function (name,minor) {
 return function (o, p) {
 var a, b;
 if (typeof o === 'object' && typeof p === 'object' && o && p) {
 a = o[name];
 b = p[name];
 if (a === b) {
 return typeof minor === 'function'? minor(o,p) : 0;
 }
 if (typeof a === typeof b) {
 return a <b? -1 : 1;
 }
 return typeof a <typeof b? -1 : 1;
 } else {
 throw {
 name: 'Error',
 message: 'Expected an object when sorting by ' + name;
 };
 }
 };
};
var s = [
 {first: 'Joe', last: 'Besser'},
 {first: 'Moe', last: 'Howard'},
 {first: 'Joe', last: 'DeRita'},
 {first: 'Shemp', last: 'Howard'},
 {first: 'Larry', last: 'Fine'},
 {first: 'Curly', last: 'Howard'}
];
s.sort(by('first'));//s is [
//{first: 'Curly', last: 'Howard'},
//{first: 'Joe', last: 'DeRita'},
//{first: 'Joe', last: 'Besser'},
//{first: 'Larry', last: 'Fine'},
//{first: 'Moe', last: 'Howard'},
//{first: 'Shemp', last: 'Howard'}
//]
var sSort = s.sort(by('last',by('first')));
console.log(sSort);
}
2 Answers

120 3

1. Error:

message: 'Expected an object when sorting by ' + name;//最后这个分号

2. Minor ( o, p ) returned.

var sSort = s.sort(by('last'), by('first')));//这里传递的第2个参数 by('first')
//minor(o, p) 即 by('first', null)

3. ( o, p ) is any of the two objects in the array s, which is defined by the sort ( ) method.
Ordering parameters are passed through by ( name ) to the o [ name ] and p [ name ].
Comparison is actually o [ name ] and p [ name ].

The number of calculations left. No care of performance.

...