Reputation: 27
here's an object.
let menu = {
width: 200,
height: 300,
title: "My menu"
};
that's the right code
function multiplyNumeric(obj) {
for (let key in obj) {
if (typeof obj[key] == 'number') {
obj[key] *= 2;
}
}
}
and here's my code
function multiplyNumeric(obj) {
for (let key in obj) {
if (typeof(obj[key]) === Number) {
obj[key] *= 2;
}
}
}
Please tell me what makes the difference?
Upvotes: 0
Views: 327
Reputation: 26
The Number() is Javascript function converts the object argument to a number that represents the object's value. If the value cannot be converted to a legal number, NaN is returned.
typeof(obj[key])
function returns, what kind of type the value is, like 'number' and string etc
Upvotes: 0
Reputation: 815
As Jonas Høgh pointed out Nummer
is a JavaScript function
A quick examlple of understanding the Number
function:
console.log(Number(true));
console.log(Number(false));
console.log(Number(new Date()));
console.log(Number("999"));
Upvotes: 0
Reputation: 14904
The difference is that 'number'
is an string and Number
is an build-in function.
console.log(typeof "number") //string
console.log(typeof Number) //function
Upvotes: 1
Reputation: 10874
The typeof
operator returns a string containing the name of the type of the operand. Number
is a function that converts its input to a number.
Upvotes: 3