-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay4EX1.js
38 lines (33 loc) · 1.53 KB
/
Day4EX1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*Write a function called each that accepts either an object or an array as its first parameter and a callback as its second parameter.
If the first parameter is an object, it should loop over the object's properties and call the callback for each one. The property value should be the first parameter passed to the callback and the property name should be the second.
If the first parameter is an array, it should loop over the array's elements and call the callback for each one. The array element should be the first parameter passed to the callback and the index should be the second.
each({
a: 1,
b: 2
}, function(val, name) {
console.log('The value of ' + name + ' is ' + val);
}); // logs 'the value of a is 1' and 'the value of b is 2'
each(['a', 'b'], function(val, idx) {
console.log('The value of item ' + idx + ' is ' + val);
}); // logs 'the value of item 0 is a' and 'the value of item 1 is b'*/
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function each(objectparam, callback) {
if (Array.isArray(objectparam) === true) {
objectparam.forEach(function(val, idx) {
callback(val, idx);
});
} else {
for (key in objectparam) {
callback(objectparam[key], key);
}
}
}
each(
{
a: 1,
b: 2
},
function(val, name) {
console.log("The value of " + name + " is " + val);
}
);