gpt4 book ai didi

javascript - 从搜索结果创建记录数组

转载 作者:行者123 更新时间:2023-11-30 18:36:45 25 4
gpt4 key购买 nike

我一直在帮助一位 friend 改进他的代码以使用搜索结果创建记录,但它并没有创建记录数组,而是只返回最后一个结果。如何获取创建的记录数组?即搜索 in 将创建一条记录:

标题:继承:继承周期,第 4 册分数:2

标题:结束的感觉分数:1

books = [
{
title: "Inheritance: Inheritance Cycle, Book 4",
author: "Christopher Paolini",
},
{
title: "The Sense of an Ending",
author: "Julian Barnes"
},
{
title: "Snuff Discworld Novel 39",
author: "Sir Terry Pratchett",
}
]
search = prompt("Title?");

function count(books, pattern) {
var result = [];
var record = {};
for (i = 0; i < books.length; i++) {
var index = -1;
result[i] = 0;
do {
index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1);
if (index >= 0) {
result[i] = result[i] + 1;
record.title = books[i].title;
record.score = result[i];
}
} while (index >= 0)
}
return record.title + " " + record.score;
}
alert(count(books, search));

最佳答案

你应该返回 result 数组,在循环中构造 record 初始分数为 0,当匹配时递增分数(而不是结果)在内循环中找到,只有当分数不为零时,才将record插入到result数组中:

function count(books, pattern) {
var result = [];
for (i = 0; i < books.length; i++) {
var record = {title: books[i].title, score: 0};
var index = -1;
do {
index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1);
if (index >= 0) {
record.score = record.score + 1
}
} while (index >= 0)
if (record.score > 0) {
result.push(record);
}
}
return result;
}

关于javascript - 从搜索结果创建记录数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8021330/

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