针对所有情况进行切换

switch for all cases

本文关键字:情况      更新时间:2023-09-26

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

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);

您想查找是否存在与之相关的名词类 字符串?- @plalx

是的,我愿意 - @pi1yau1u

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

演示

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);
});

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

在这种情况下,您不需要使用该switch。但是"对于所有情况",您将使用default: