gpt4 book ai didi

javascript - 切换所有情况

转载 作者:行者123 更新时间:2023-11-30 17:49:10 26 4
gpt4 key购买 nike

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

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

最佳答案

You want to find if there was a noun class instanciated with that string? - @plalx

Yes i do - @pi1yau1u

在这种情况下,您可以使用映射来存储所有新创建的实例并实现一个 API,该 API 允许您通过名称 检索它们或检索整个列表。我还实现了一个 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);
});

关于javascript - 切换所有情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com