How can I convert the quotargumentsquot object to an array in JavaScript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype

It s trivially easy to construct a new array from an arguments object with a simple for loop. For example, this function sorts its arguments:

function sortArgs() {
    var args = [];
    for (var i = 0; i < arguments.length; i++)
        args[i] = arguments[i];
    return args.sort();
}

However, this is a rather pitiful thing to have to do simply to get access to the extremely useful JavaScript array functions. Is there a built-in way to do it using the standard library?

Answers

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

function sortArgs() {
    var args = Array.prototype.slice.call(arguments);
    return args.sort();
}

http://es5.github.io/#x15.4.4.10 http://es5.github.io/#x15.4.4.10

NOTE  : The slice function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the slice function can be applied successfully to a host object is implementation-dependent.

Therefore, slice works on anything that has a length property, which arguments conveniently does.


If Array.prototype.slice is too much of a mouthful for you, you can abbreviate it slightly by using array literals:

var args = [].slice.call(arguments);

However, I tend to feel that the former version is more explicit, so I d prefer it instead. Abusing the array literal notation feels hacky and looks strange.

If you are able to use ES6 you can use:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

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

document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/960866/how-can-i-convert-the-arguments-object-to-an-array-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils