我正在开展一个codecademy练习,我们使用for-in语句来循环访问一个对象,并通过检查语言对象中属性的值是否是使用 typeof
I'm working on a codecademy exercise where we use for-in statements to loop through an object and print hello in different languages by checking to see if the values of the properties in the languages object are strings using typeof
我查看该值是否为字符串不起作用。我的循环给了我这个结果
my check to see if the value is a string is not working. my loops giving me this result
english french notALanguage spanish代码
var languages = { english: "Hello!", french: "Bonjour!", notALanguage: 4, spanish: "Hola!" }; // print hello in the 3 different languages for(var hello in languages){ var value = hello; if (typeof value === "string"){ console.log(value); } }这些是练习的说明
如果你真的想到它,对象就不那么陌生了!
Objects aren't so foreign if you really think about it!
记住你可以想象通过使用typeof myVariable输出变量的类型。我们现在关注的类型是对象,字符串和数字。
Remember you can figure out the type of a variable by using typeof myVariable. Types we are concerned with for now are "object", "string", and "number".
回想for-in循环:
Recall the for-in loop:
for(var x in obj){executeSomething(); }
for(var x in obj) { executeSomething(); }
这将逐个遍历obj的所有属性,并在循环的每次运行中将的属性名称分配给x。
This will go through all the properties of obj one by one and assign the property name to x on each run of the loop.
让我们结合我们对这两个概念的了解。
Let's combine our knowledge of these two concepts.
检查语言对象。三个属性是字符串,而一个是数字。
Examine the languages object. Three properties are strings, whereas one is a number.
使用for-in循环打印出三种打招呼方式。在循环中,您应该检查属性值是否为字符串,这样您不会意外打印数字。
Use a for-in loop to print out the three ways to say hello. In the loop, you should check to see if the property value is a string so you don't accidentally print a number.
推荐答案
那是因为你正在检查对象的键。要检查实际值,您应该执行类似 object [key] 的操作。试试这个:
That's because you're checking the key of the object. To check the actual value, you should be doing something like object[key]. Try this:
var languages = { english: "Hello!", french: "Bonjour!", notALanguage: 4, spanish: "Hola!" }; // print hello in the 3 different languages for(var hello in languages){ var value = languages[hello]; if (typeof value === "string"){ console.log(value); } }更多推荐
JavaScript:使用typeof来检查字符串
发布评论