JavaScript:使用typeof来检查字符串

编程入门 行业动态 更新时间:2024-10-21 13:23:49
本文介绍了JavaScript:使用typeof来检查字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在开展一个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来检查字符串

本文发布于:2023-11-08 13:50:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569550.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   JavaScript   typeof

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!