gpt4 book ai didi

javascript - 无法读取未定义的属性 'score'

转载 作者:行者123 更新时间:2023-12-02 16:49:42 27 4
gpt4 key购买 nike

我知道还有很多其他类似的问题与该领域有关,但没有一个答案有效。就我而言,我有以下代码,我试图按分数降序对记录数组进行排序。

function score(string, pattern){
string = string.toLowerCase();
pattern = pattern.toLowerCase();

var position = 0;
var count = 0;
while (true) {
var index = string.indexOf(pattern, position);
if (index == -1) break;
count++;
position = index + 1;
}
return(count);
}

function urlScores(web, pattern){
var records = {};
var results = [];
var n = 0;
for(var i = 0; i < web.length; i++){
n = score(web[i].content, pattern);
if(n != 0){
records.url = web[i].url;
records.score = n;
results[results.length] = {url: records.url, score: records.score};
}
}
return(JSON.stringify(results));
}

function rankedScores(web, pattern){
results = JSON.parse(urlScores(web, pattern));
var temp = 0;
var tempUrl = '';
while(counter < results.length){
for(var i in results){
numbers[numbers.length] = results[i].score;
if(results[i].score < results[i + 1].score){
temp = results[i].score;
tempUrl = results[i].url;
results[i] = {url: results[i+1].url, score: results[i+1].score};
results[i + 1] = {url: tempUrl, score: temp};
}
}
counter++;
}
alert(JSON.stringify(results));
}

最后一个函数给我带来了问题。如果用户运行以下命令:

var web = [ {url : "www.southampton.ac.uk", content : "Southampton University offers degree programmes and world class research test." } , {url : "www.xyz.ac.uk", content : "An alternative University test test test" } , {url : "www", content : "Yet another University test" } ];

rankedScores(web, 'test');

它应该输出相同的数组,但按降序排列。相反,我得到了无法读取未定义的属性“分数”。任何人都可以看到我哪里出了问题吗?
谢谢
另外,我们不允许使用 .sort()!

最佳答案

function rankedScores(web, pattern){
var results = JSON.parse(urlScores(web, pattern));
var temp = 0;
var tempUrl = '';
var counter = 0;
var numbers = [], i, len = results.length;

while (counter < results.length){
for (i = 0; i < len - 1; i++){
numbers[numbers.length] = results[i].score; /// ????

if (results[i].score < results[i + 1].score){
temp = results[i].score;
tempUrl = results[i].url;

results[i] = {url: results[i+1].url, score: results[i + 1].score};
results[i + 1] = {url: tempUrl, score: temp};
}
}

counter++;
}

alert(JSON.stringify(results));
}

关于javascript - 无法读取未定义的属性 'score',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26787610/

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