可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
The arguments
object in JavaScript is an odd wart—it acts just like an array in most situations, but it\'s not actually an array object. Since it\'s really something else entirely, it doesn\'t have the useful functions from Array.prototype
like forEach
, sort
, filter
, and map
.
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?
回答1:
ES6 using rest parameters
If you are able to use ES6 you can use:
Rest Parameters
function sortArgs(...args) {
return args.sort(function (a, b) { return a - b; });
}
document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();
As you can read in the link
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
If you are curious about the ...
syntax, it is called Spread Operator and you can read more here.
ES6 using array.from()
Using array.from:
function sortArgs() {
return Array.from(arguments).sort(function (a, b) { return a - b; });
}
document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();
Array.from
simply convert Array-like or Iterable objects into Array instances.
ES5
You can actually just use Array
\'s slice
function on an arguments object, and it will convert it into a standard JavaScript array. You\'ll just have to reference it manually through Array\'s prototype:
function sortArgs() {
var args = Array.prototype.slice.call(arguments);
return args.sort();
}
Why does this work? Well, here\'s an excerpt from the ECMAScript 5 documentation itself:
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.
回答2:
It\'s also worth referencing this Bluebird promises library wiki page that shows how to manage the arguments
object into array in a way that makes the function optimizable under V8 JavaScript engine:
function doesntLeakArguments() {
var args = new Array(arguments.length);
for(var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
return args;
}
This method is used in favor of var args = [].slice.call(arguments);
. The author also shows how a build step can help reduce the verbosity.
回答3:
function sortArgs(){ return [].slice.call(arguments).sort() }
// Returns the arguments object itself
function sortArgs(){ return [].sort.call(arguments) }
Some array methods are intentionally made not to require the target object to be an actual array. They only require the target to have a property named length and indices (which must be zero or larger integers).
[].sort.call({0:1, 1:0, length:2}) // => ({0:0, 1:1, length:2})
回答4:
Use:
function sortArguments() {
return arguments.length === 1 ? [arguments[0]] :
Array.apply(null, arguments).sort();
}
Array(arg1, arg2, ...)
returns [arg1, arg2, ...]
Array(str1)
returns [str1]
Array(num1)
returns an array that has num1
elements
You must check number of arguments!
Array.slice
version (slower):
function sortArguments() {
return Array.prototype.slice.call(arguments).sort();
}
Array.push
version (slower, faster than slice):
function sortArguments() {
var args = [];
Array.prototype.push.apply(args, arguments);
return args.sort();
}
Move version (slower, but small size is faster):
function sortArguments() {
var args = [];
for (var i = 0; i < arguments.length; ++i)
args[i] = arguments[i];
return args.sort();
}
Array.concat
version (slowest):
function sortArguments() {
return Array.prototype.concat.apply([], arguments).sort();
}
回答5:
If you\'re using jQuery, the following is a good deal easier to remember in my opinion:
function sortArgs(){
return $.makeArray(arguments).sort();
}
回答6:
Here is benchmark of several methods converting arguments into array.
As for me, the best solution for small amount of arguments is:
function sortArgs (){
var q = [];
for (var k = 0, l = arguments.length; k < l; k++){
q[k] = arguments[k];
}
return q.sort();
}
For other cases:
function sortArgs (){ return Array.apply(null, arguments).sort(); }
回答7:
I recommend using ECMAScript 6 spread operator, which will Bind trailing parameters to an array. With this solution you don\'t need to touch the arguments
object and your code will be simplified. The downside of this solution is that it does not work across most browsers, so instead you will have to use a JS compiler such as Babel. Under the hood Babel transforms arguments
into a Array with a for loop.
function sortArgs(...args) {
return args.sort();
}
If you can not use a ECMAScript 6, I recommend looking at some of the other answers such as @Jonathan Fingland
function sortArgs() {
var args = Array.prototype.slice.call(arguments);
return args.sort();
}
回答8:
Lodash:
var args = _.toArray(arguments);
in action:
(function(){ console.log(_.toArray(arguments).splice(1)); })(1, 2, 3)
produces:
[2,3]
回答9:
Use Array.from()
, which takes an array-like object (such as arguments
) as argument and converts it to array:
(function() {
console.log(Array.from(arguments));
}(1, 2, 3));
Note that it doesn\'t work in some older browsers like IE 11, so if you want to support these browsers, you should use Babel.
回答10:
function sortArg(){
var args = Array.from(arguments); return args.sort();
}
function sortArg(){
var args = Array.from(arguments);
return args.sort();
}
console.log(sortArg(\'a\', \'b\', 1, 2, \'34\', 88, 20, \'19\', 39, \'d\', \'z\', \'ak\', \'bu\', 90));
回答11:
In ECMAScript 6 there\'s no need to use ugly hacks like Array.prototype.slice()
. You can instead use spread syntax (...
).
(function() {
console.log([...arguments]);
}(1, 2, 3))
It may look strange, but it\'s fairly simple. It just extracts arguments
\' elements and put them back into the array. If you still don\'t understand, see this examples:
console.log([1, ...[2, 3], 4]);
console.log([...[1, 2, 3]]);
console.log([...[...[...[1]]]]);
Note that it doesn\'t work in some older browsers like IE 11, so if you want to support these browsers, you should use Babel.
回答12:
Another Answer.
Use Black Magic Spells:
function sortArguments() {
arguments.__proto__ = Array.prototype;
return arguments.slice().sort();
}
Firefox, Chrome, Node.js, IE11 are OK.
回答13:
Try using Object.setPrototypeOf()
Explanation: Set prototype
of arguments
to Array.prototype
function toArray() {
return Object.setPrototypeOf(arguments, Array.prototype)
}
console.log(toArray(\"abc\", 123, {def:456}, [0,[7,[14]]]))
Explanation: Take each index of arguments
, place item into an array at corresponding index of array.
could alternatively use Array.prototype.map()
function toArray() {
return [].map.call(arguments, (_,k,a) => a[k])
}
console.log(toArray(\"abc\", 123, {def:456}, [0,[7,[14]]]))
Explanation: Take each index of arguments
, place item into an array at corresponding index of array.
for..of
loop
function toArray() {
let arr = []; for (let prop of arguments) arr.push(prop); return arr
}
console.log(toArray(\"abc\", 123, {def:456}, [0,[7,[14]]]))
or Object.create()
Explanation: Create object, set properties of object to items at each index of arguments
; set prototype
of created object to Array.prototype
function toArray() {
var obj = {};
for (var prop in arguments) {
obj[prop] = {
value: arguments[prop],
writable: true,
enumerable: true,
configurable: true
}
}
return Object.create(Array.prototype, obj);
}
console.log(toArray(\"abc\", 123, {def: 456}, [0, [7, [14]]]))
回答14:
Benshmarck 3 methods :
function test()
{
console.log(arguments.length + \' Argument(s)\');
var i = 0;
var loop = 1000000;
var t = Date.now();
while(i < loop)
{
Array.prototype.slice.call(arguments, 0);
i++;
}
console.log(Date.now() - t);
i = 0,
t = Date.now();
while(i < loop)
{
Array.apply(null, arguments);
i++;
}
console.log(Date.now() - t);
i = 0,
t = Date.now();
while(i < loop)
{
arguments.length == 1 ? [arguments[0]] : Array.apply(null, arguments);
i++;
}
console.log(Date.now() - t);
}
test();
test(42);
test(42, 44);
test(42, 44, 88, 64, 10, 64, 700, 15615156, 4654, 9);
test(42, \'truc\', 44, \'47\', 454, 88, 64, \'@ehuehe\', 10, 64, 700, 15615156, 4654, 9,97,4,94,56,8,456,156,1,456,867,5,152489,74,5,48479,89,897,894,894,8989,489,489,4,489,488989,498498);
RESULT?
0 Argument(s)
256
329
332
1 Argument(s)
307
418
4
2 Argument(s)
375
364
367
10 Argument(s)
962
601
604
40 Argument(s)
3095
1264
1260
Enjoy !
回答15:
function sortArgs(...args) {
return args.sort(function (a, b) { return a - b; });
}
document.body.innerHTML = sortArgs(1, 2, 3, 4).toString();
回答16:
Although rest parameters work well, if you want to continue to use arguments
for some reason, consider
function sortArgs() {
return [...arguments].sort()
}
[...arguments]
can be considered a sort of alternative to Array.from(arguments)
, which also works perfectly well.
An ES7 alternative is an array comprehension:
[for (i of arguments) i].sort()
This could be easiest if you want to process or filter the arguments prior to sorting:
[for (i of arguments) if (i % 2) Math.log(i)].sort()
回答17:
function x(){
var rest = [...arguments]; console.log(rest);return
rest.constructor;
};
x(1,2,3)
I tried simple destructing technique
回答18:
The Arguments object is only available inside a function body. Although you can index the Arguments Object like an array, it is not an array. It does not have any array properties other than length.
// function arguments length 5
function properties(a,b,c,d,e){
var function_name= arguments.callee.name
var arguments_length= arguments.length;
var properties_length= properties.length;
var function_from= properties.caller.name;
console.log(\'I am the function name: \'+ function_name);
console.log(\'I am the function length, I am function spacific: \'+ properties_length);
console.log(\'I am the arguments length, I am context/excution spacific: \'+ arguments_length);
console.log(\'I am being called From: \'+ function_from );
}
// arguments 3
function parent(){
properties(1,2,3);
}
//arguments length 3 because execution spacific
parent();
Although it can be indexed like an array as you can see in this example:
function add(){
var sum=0;
for(var i=0; i< arguments.length;i++){
sum = sum + arguments[i];
}
return sum;
}
console.log(add(1,2,3));
However, the Arguments object is not an array and does not have any other properties other than length.
You can convert the arguments object into an array at which point you can access the Arguments object.
There are many ways you can access the arguments object inside a function body, and these include:
- you can call the Array.prototoype.slice.call method.
Array.prototype.slice.call(arguments)
function giveMeArgs(arg1,arg2){
var args = Array.prototype.slice.call(arguments);
return args
}
console.log( giveMeArgs(1,2));
- you can use the array literal
[].slice.call(arguments).
function giveMeArgs(arg1,arg2){
var args = [].slice.call(arguments);
return args;
}
console.log( giveMeArgs(1,2) );
- you can use Rest ...
function giveMeArgs(...args){
return args;
}
console.log(giveMeArgs(1,2))
- you can use spread [...]
function giveMeArgs(){
var args = [...arguments];
return args;
}
console.log(giveMeArgs(1,2));
- you can use Array.from()
function giveMeArgs(){
var args = Array.from(arguments);
return args;
}
console.log(giveMeArgs(1,2));
回答19:
You can create a reusable function to do it with any arguments, the simplest one is something like this:
function sortArgs() {
return [...arguments].sort();
}
sortArgs(\'ali\', \'reza\', 1, 2, \'a\'); //[1, 2, \"a\", \"ali\", \"reza\"];
Spread syntax can be used in ES6 and above...
But if you\'d like to use something compatible with ES5 and below, you can use Array.prototype.slice.call
, so you code looks like this:
function sortArgs() {
return Array.prototype.slice.call(arguments).sort();
}
sortArgs(\'ali\', \'reza\', 1, 2, \'a\'); //[1, 2, \"a\", \"ali\", \"reza\"];
There are also few other ways to do this, for Example using Array.from
or loop through the arguments and assign them to a new array...
回答20:
This is a very old question, but I think I have a solution that is slightly easier to type than previous solutions and doesn\'t rely on external libraries:
function sortArguments() {
return Array.apply(null, arguments).sort();
}