配列内のプロトタイプ関数を使用してスコープの問題の周りに脳をラッピングする際に問題が発生しています。私はそれを静的な項目で動作させることができますが、配列で作業するために一般化しようとすると、 "関数ではありません"というエラーが表示されます。ここにコードの私の現在の演出があります。どんな助けもありがとう。配列のソート中にプロトタイプ関数にアクセスしますか?
function Automobile(year, make, model, type) {
this.year = year; //integer (ex. 2001, 1995)
this.make = make; //string (ex. Honda, Ford)
this.model = model; //string (ex. Accord, Focus)
this.type = type; //string (ex. Pickup, SUV)
}
Automobile.prototype.logMe = function(bool) {
console.log("Working"); //testing function
if (bool == true) {
console.log(this);
}
};
/*Sample Array*/
var automobiles = [
new Automobile(1995, "Honda", "Accord", "Sedan"),
new Automobile(1990, "Ford", "F-150", "Pickup"),
new Automobile(2000, "GMC", "Tahoe", "SUV"),
new Automobile(2010, "Toyota", "Tacoma", "Pickup"),
new Automobile(2005, "Lotus", "Elise", "Roadster"),
new Automobile(2008, "Subaru", "Outback", "Wagon")
];
/*This function sorts arrays using an arbitrary comparator.*/
function sortArr(comparator, array) {
array.sort(function(a, b) {
return comparator(a, b);
});
return array;
}
function exComparator(int1, int2) {
if (int1 > int2) {
return true;
} else {
return false;
}
}
function yearComparator(auto1, auto2) {
return exComparator(auto1.year, auto2.year);
}
/* Output*/
console.log("*****");
console.log("The cars sorted by year are:");
forEach(sortArr(yearComparator, automobiles), automobiles.logMe(true)); //This is not right!
function forEach(array, doStuff) {
for (var i = 0; i < array.length; i++)
doStuff(array[i]);
}
ソートコンパレータ関数は 'true'または' false'を返すものではありません。代わりに、負の数、ゼロ、または正の数を返して、最初の値が前の値になるか、同じであるか、または2番目の値が最初の値よりも前になる必要があることを示します。 – Pointy
また、あなたの 'sortArr'関数は' array.sort(comparator) 'と機能的に同じです – Alnitak
[あなたの比較関数は無効です](http://stackoverflow.com/q/24080785/1048572)、それはあなたの問題ではありません'forEach'で持っています。 – Bergi