添加用于对数组进行排序的库函数得到未定义

问题描述 投票:0回答:1

我正在尝试添加用于对数组中的项目进行排序的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());

参考:

enter image description herehttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

javascript ecmascript-6
1个回答
1
投票

您需要返回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; }

1
投票

尝试返回结果

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());
© www.soinside.com 2019 - 2024. All rights reserved.