gpt4 book ai didi

javascript - 如何通过从对象获取来循环将消息添加到字符串中?

转载 作者:行者123 更新时间:2023-12-03 03:00:34 25 4
gpt4 key购买 nike

我制作自己的字典,我将所有单词保存在一个对象中。我通过将一些内容放入内容变量来使用并循环查找单词,如果找到哪个单词,则应添加消息。我该怎么做?

<小时/>
  • 我能有这样的结果吗

Boom 是一家美国公司。它想要制造一架新飞机。计划在 2023 年拥有一架飞机 这架飞机(将来会发生)是超音速的。它将(将来发生)从伦敦飞到纽约只需三个小时。航类(乘坐飞机的旅程)机票(将来发生的)不会非常昂贵。它(将来会发生)的费用将与标准商务舱机票一样高。

<小时/>

我的代码

let content = "Boom is an American company. It wants to make a new plane. The plan is to have a plane in 2023 The plane will be supersonic. It will fly from London to New York in three hours. The flight ticket will not be extremely expensive. It will cost as much as a standard business class ticket.";


var myDictionary =
{
will: "to happen in the future",
flight: "a journey in an aircraft",
cost: "the amount of money needed to buy",
particular: "or this and not any other"
}


for(let i in myDictionary) {//each word


for(i=0;/**/)//this word found, such as "will" have to 4 rounds
{
/*loop for find, how many position in this word.
if this word has 2 positions that first loop add my transalate message after the fist position of word and round 2, if more it's have to keep loop until no found this position and out to main loop for find next word
add in the second position.
*/
generate(i);
}

}


function generate(word)
{

let find_position = content.indexOf(word);
console.log(find_position);
let length_of_word = word.length;
let find_position_after_word = find_position + length_of_word;
let transalate_word = getProperty(word);
let output = content.slice(0, find_position_after_word), transalate_word, content.slice(find_position_after_word)].join('');
}

function getProperty(word_for_transalate)
{
return myDictionary[word_for_transalate];
}

最佳答案

尝试reducereplace

var output = Object.keys(myDictionary).reduce( function(a,b,i){
if (i == 1)
{
a = content.replace( new RegExp( a, "gi" ), a + "(" + myDictionary[ a ] + ")" );
}
a = a.replace( new RegExp( b, "gi" ), b + "(" + myDictionary[ b ] + ")" );
return a;
});

演示

var content = "Boom is an American company. It wants to make a new plane. The plan is to have a plane in 2023 The plane will be supersonic. It will fly from London to New York in three hours. The flight ticket will not be extremely expensive. It will cost as much as a standard business class ticket.";

var myDictionary = {
will: "to happen in the future",
flight: "a journey in an aircraft",
cost: "the amount of money needed to buy",
particular: "or this and not any other"
};

var output = Object.keys(myDictionary).reduce(function(a, b, i) {
if (i == 1) {
a = content.replace(new RegExp(a, "gi"), a + "(" + myDictionary[a] + ")");
}
a = a.replace(new RegExp(b, "gi"), b + "(" + myDictionary[b] + ")");
return a;
});

console.log( output );

关于javascript - 如何通过从对象获取来循环将消息添加到字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47409651/

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