我正在尝试添加用于对数组中的项目进行排序的Library函数。虽然我知道链接和方式,但是当尝试使一个库函数执行时,这不起作用。有人可以帮助我,因为结果是undefined
。
var arr1 = [5, 4, 2, 6, 9, 2, 8, 1, 6];
Array.prototype.sortItems = function(){
this.sort((a,b) => a - b);
}
console.log(arr1.sortItems());
参考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
您需要返回this.sort
var arr1 = [5, 4, 2, 6, 9, 2, 8, 1, 6];
Array.prototype.sortItems = function(){
return this.sort((a,b) => a - b);
}
console.log(arr1.sortItems());
.as-console-wrapper { max-height: 100% !important; top: 0; }
尝试返回结果
var arr1 = [5, 4, 2, 6, 9, 2, 8, 1, 6];
Array.prototype.sortItems = function(){
return this.sort((a,b) => a - b);
}
console.log(arr1.sortItems());