gpt4 book ai didi

javascript - 在 javascript 中为数组和数组数组创建函数。

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

对 javascript 还很陌生,并且在数组中的数组方面遇到很多麻烦。我的任务是从两个数组中提取名称和引号。我的任务是创建一个函数,可以在其中输入引号并吐出响应“约翰说:Blah blah blah”,它们就是这样设置的。

let names = [ John, James, Joe, Justin] 
let quotes = [
[ "Help me."
"Blah blah blah blah"
"Blah blah blah" ]
[ "Blah blah blah"
"Quote here" ]]

现在的名字和引述比我为简洁起见而停止的还要多。名称和引号都匹配,即名称数组中的第一个名称与引号数组中的第一个引号数组相对应。这是我为其编写代码的尝试。

 function whoSaidThis (quote) {
var index = quotes.indexOf(quote);
return crewmembers.index
}

这返回为未定义,我不明白为什么。

最佳答案

为什么返回 undefined :

您的函数返回undefined,因为您没有初始化对象crewmembers的属性index,因此您正在尝试访问的属性>crewmembers 不存在,因此返回 undefined

这是 Javascript 的方式告诉您“嘿,船员对象不存在索引属性”

此外,关于您的尝试,您正在尝试在 qoutes 数组中搜索 qoute,而实际上应该搜索 qoute code> 在 qoutes 数组的每个项目中。

当您命中匹配项时,您将返回该项目数组的索引,该索引是该项目数组在 qoute 数组内的索引。

你可以这样做:

var names = ["John", "James", "Joe", "Justin"];
var quotes = [["Help me.", "Blah blah blah blah", "Blah blah blah"],["Blah blah blah", "Quote here"],["sample qoute"],["sample qoute again"]];

function whoSaidThis(qoute){
//Iterate over qoutes array
for(var i=0;i<quotes.length;i++) {
//check if any of the items in qoutes array contain the qoute
if(quotes[i].indexOf(qoute) !== -1 ) {
break;
}
}
//returns undefined if qoute not foundin the qoutes array
return i === quotes.length ? undefined : names[i] + " says : " + qoute;
};

console.log(whoSaidThis("sample qoute"));

关于javascript - 在 javascript 中为数组和数组数组创建函数。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46571380/

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