[英]How do I alert(); the result of this JS function?
I am doing the following exercise (while studying JS):我正在做以下练习(在学习 JS 时):
"Create a function multiplyNumeric(obj)
that multiplies all numeric properties of obj by 2." “创建一个函数
multiplyNumeric(obj)
, multiplyNumeric(obj)
所有数字属性乘以 2。”
The solution is:解决办法是:
function multiplyNumeric(obj) {
for (let key in obj) {
if (typeof obj[key] == 'number') {
obj[key] *= 2;
}
}
}
multiplyNumeric
does not need to return anything, it should modify the object in-place. multiplyNumeric
不需要返回任何东西,它应该就地修改对象。
But what if I want to alert it?但是如果我想提醒它怎么办? I tried different solutions, but I can't get it right..is there a reason why it doesn't alert or I'm just doing it wrong?
我尝试了不同的解决方案,但我无法正确解决..是否有理由不提醒或我只是做错了? (exercise reference here: https://javascript.info/object )
(此处练习参考: https : //javascript.info/object )
I tried:我试过:
let obj = {
first: 100,
second: 200,
third: "Hello"
};
function multiplyNumeric(obj) {
for (let key in obj) {
if (typeof obj[key] == 'number') {
obj[key] *= 2;
}
}
}
alert(obj);
In this case it alerts: [object Object]
在这种情况下,它会发出警报:
[object Object]
I also tried alert(obj.first);
我也试过
alert(obj.first);
but it alerts 100. I tried to put the alert(obj);
但它提醒 100。我试图把
alert(obj);
inside the curly braces but it does nothing.在花括号内,但它什么也不做。
Please be patient, I am just a beginner...请耐心等待,我只是一个初学者......
Consider using console.log()
as it will display objects nicely.考虑使用
console.log()
因为它会很好地显示对象。 However if you are determined to use alert()
you should know that alert()
only takes in strings.但是,如果您决定使用
alert()
您应该知道alert()
只接受字符串。 So try alert(JSON.stringify(obj))
所以试试
alert(JSON.stringify(obj))
to alert each key in obj seperatly:分别提醒 obj 中的每个键:
function multiplyNumeric(obj) {
for (let key in obj) {
if (typeof obj[key] == 'number') {
obj[key] *= 2;
alert(obj[key]);
}
}
}
if you want to alert it together, after all the multiply finish, than如果你想一起提醒它,在所有的乘法完成之后,比
function multiplyNumeric(obj) {
for (let key in obj) {
if (typeof obj[key] == 'number') {
obj[key] *= 2;
}
}
alert(JSON.stringify(obj));
}
Use console.log() let obj = { first: 100, second: 200, third: "Hello" };使用 console.log() let obj = { first: 100, second: 200, third: "Hello" };
function multiplyNumeric(obj) {
for (let key in obj) {
if (typeof obj[key] == 'number') {
obj[key] *= 2;
}
}
}
Console.log(obj); Console.log(obj);
I don't see any alert()
in the question.我在问题中没有看到任何
alert()
。 Since, I don't have much reputation to comment, I am writing the code which works.因为,我没有多少声誉可以评论,所以我正在编写有效的代码。
function multiplyNumeric(obj) {
for (let key in obj) {
if (typeof obj[key] == 'number') {
obj[key] *= 2;
}
}
}
var obj = {'number' : 2};
multiplyNumeric(obj);
alert(obj['number']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.