简体   繁体   中英

Why do I keep getting a TypeError: args.sort is not a function?

function getIndexToIns(arr, num) {

  var args = Array.prototype.join.call(arguments);

  function compareNumbers(a, b) {
    return a - b;
  }
  args.sort(compareNumbers);

  return args;

}

getIndexToIns([40, 60], 50);

The error was thrown simply because Array.prototype.join returns a string. In order to convert array-like objects to arrays, you need to use Array.prototype.slice.call instead.

Replace

 var args = Array.prototype.join.call(arguments);

with this

 var args = Array.prototype.slice.call(arguments);

or with Function.prototype.apply

var args = Array.apply(null, arguments);

or with Array.from

var args = Array.from(arguments);

The cleanest solution is ES6 rest parameters

function getIndexToIns(...args) {

  function compareNumbers(a, b) {
    return a - b;
  }
  args.sort(compareNumbers);

  return args;

}

getIndexToIns([40, 60], 50);

Because Array.prototype.join.call(arguments); will return a string rather than an array and String doesn't have a sort method.

Replace

var args = Array.prototype.join.call(arguments);

with

var args = Array.apply(null, arguments);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM