切换所有情况

时间:2013-10-18 11:47:58

标签: javascript switch-statement

我想检查输入的字符串是否属于类名称。

var answer = prompt("enter sentence").toLowerCase();

function Noun(name) {
    this.name = name;
}

spoon = new object("noun");

我可以找到像wwwspoonwww这样的子字符串之间的匹配吗?

 var analysis = function(string) {
    switch (true) {
        case /any string/.test(string):
        if (?){
            console.log("noun");
        }
        else {
            console.log("not noun")
        };
        break;
    }
 };
 analysis(answer);

2 个答案:

答案 0 :(得分:1)

要检查某个字符串是否在另一个字符串中,您可以使用str.indexOf(string);

在这种情况下,您无需使用switch。但“对于所有情况”,您将使用default:

答案 1 :(得分:1)

  

你想找到是否有与之相关的名词类   串? - @plalx

     

是的我 - @ pi1yau1u

在这种情况下,您可以使用地图存储所有新创建的实例,并实现一个API,允许您通过 name 检索它们或检索整个列表。我还实现了一个findIn实例方法,它将返回指定字符串中该名词的索引,如果找不到则返回-1。

DEMO

var Noun = (function (map) {

    function Noun(name) {
        name = name.toLowerCase();

        var instance = map[name];

        //if there's already a Noun instanciated with that name, we return it
        if (instance) return instance;

        this.name = name;

        //store the newly created noun instance
        map[name] = this;
    }

    Noun.prototype.findIn = function (s) {
        return s.indexOf(this.name);
    };

    Noun.getByName = function (name) {
        return map[name.toLowerCase()];
    };

    Noun.list = function () {
        var m = map, //faster access
            list = [], 
            k;

        for (k in m) list.push(m[k]);

        return list;
    };

    return Noun;

})({});

new Noun('table');
new Noun('apple');

//retrieve a noun by name
console.log('retrieved by name :', Noun.getByName('table'));

//check if a string contains some noun (without word boundaries)
var s = 'I eat an apple on the couch.';

Noun.list().forEach(function (noun) {
    if (noun.findIn(s) !== -1) console.log('found in string: ', noun);
});