Skip to content

Commit da652e0

Browse files
committed
Added details about converting to an array to access array methods - divyanshu-rawat#4
1 parent 52d1be2 commit da652e0

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

The arguments object.js

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ var x = 2,y = 4;
88

99
function arguments(x,y){
1010

11-
// console.log(arguments);
12-
// console.log(Array.prototype.slice.call(arguments));
11+
// console.log(arguments);
12+
// console.log(Array.prototype.slice.call(arguments));
1313

14-
// Because this conversion is slow, it is not recommended to use it in performance-critical sections of code.
14+
// Because this conversion is slow, it is not recommended to use it in performance-critical sections of code.
1515
};
1616

1717
arguments(x,y);
@@ -22,10 +22,29 @@ arguments(x,y);
2222
// Due to this, it is not possible to use standard array methods like push, pop or slice on arguments. While iteration with a plain for loop works just fine
2323
// it is necessary to convert it to a real Array in order to use the standard Array methods on it.
2424

25+
function baz(c, d) {
26+
console.log(arguments); // { 0: 1, 1: 2 }
27+
for(var i = 0; i < arguments.length; i++) {
28+
console.log(arguments[i]); // 1, 2
29+
}
30+
31+
args.forEach(arg => console.log(arg)); // TypeErrror
32+
}
33+
34+
baz(1, 2);
35+
2536
// Converting to an Array
2637

27-
// The code below will return a new Array containing all the elements of the arguments object.
38+
// The code below will return a new Array containing all the elements of the arguments object. You then have access to all typical
39+
// Array methods.
40+
41+
function baz(c, d) {
42+
var args = [].slice.call(arguments);
43+
console.log(args); // [1, 2]
44+
args.forEach(arg => console.log(arg)); // 1, 2
45+
}
2846

47+
baz(1, 2);
2948

3049
// Passing Arguments
3150

@@ -56,7 +75,7 @@ function bar(a, b) {
5675

5776
function boo(a, b, c) {
5877

59-
console.log(arguments);
78+
console.log(arguments);
6079

6180
arguments[0] = 2;
6281

0 commit comments

Comments
 (0)