JavaScript:使用typeof来检查字符串 [英] JavaScript: using typeof to check if string

查看:104
本文介绍了JavaScript:使用typeof来检查字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开展一个codecademy.com练习,我们使用for-in语句来循环访问一个对象,并通过检查语言对象中属性的值是否是使用<$的字符串来打印不同语言的hello c $ c> typeof

I'm working on a codecademy.com 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来检查字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆