我有一系列名字:
names = [name1, name2, name3...]
对应于包含与名称数组对应的引号的数组数组。
quotes = [[q#1a, q#2b..], [q#1c, q#2d..], [q#1e, q#2f]]
我尝试创建一个可以输入特定引号的函数(例如q#1c
),console.log将返回说出来的人的姓名。
我被困住并且一直未定义。有什么建议?以下是我到目前为止的情况。
function findQuote(quote) {
return quote == `"q#1c"`;
}
let whoSaidIt = (c) => {
let quote = quotes.index;
return `${name[c]} said ${quotes[c]}.`;
};
console.log(whoSaidIt(quotes.findIndex(findQuote)));
答案 0 :(得分:0)
如果引号是您想要查找的,那么将它们存储在嵌套数组中会使这不必要地变得复杂。 我会将引号存储在一个平面数组中并将它们映射到名称。 也许是这样的:
var names = ["Einstein","Trump","Pikachu"];
var quotes = ["E=mcc","Sad.","Pika!","Two things are stupid."];
var quotees = [0,1,2,0];
function whoSaidIt(q) {
return names[quotees[quotes.indexOf(q)]];
}
document.getElementById("out").innerHTML=whoSaidIt("E=mcc");

<div id="out"></div>
&#13;
答案 1 :(得分:0)
let names = ['name1', 'name2', 'name3'];
let quotes = [['q#1a', 'q#2b'], ['q#1c', 'q#2d'], ['q#1e', 'q#2f']];
let whoSaidIt = (c) => quotes.reduce((a, v, i) => quotes[i].includes(c) ? `${names[i]} said ${c}.` : a, '') || 'No-one said that!';
whoSaidIt('q#1c'); //Returns 'name2'
假设names.length === quotes.length和names [I]表示引号[I],您可以使用reduce来获得答案。一个是&#39;&#39;默认情况下,由第二个属性决定。
我们只需在找到引号时设置返回消息。我可以用名字来得到说出这句话的人。如果未找到匹配项,我们可以使用||。
保留默认消息您可能需要考虑使用对象来存储名称和引号,因为它可能更容易引用。 {&#39; q#1a&#39;:&#39; name1&#39;,...}
答案 2 :(得分:0)
您的findQuote
函数仍然需要查看数组(因为quotes
是数组数组),您可以使用includes
。此外,如果您将引号传递给搜索而不是在函数中对其进行硬编码,则会更实用。然后,您可以在findQuote
:
findIndex
var names = ['John', 'Helen', 'Anna'];
var quotes = [['q#1a', 'q#2b'], ['q#1c', 'q#2d'], ['q#1e', 'q#2f']];
function findQuote(quote, quotes) {
return quotes.includes(quote);
}
let whoSaidIt = (c) => {
return names[c];
};
let quote = "q#1c";
console.log(`${whoSaidIt(quotes.findIndex(findQuote.bind(null,quote)))} said ${quote}`);
&#13;
以较短的方式:
const names = ['John', 'Helen', 'Anna'],
quotes = [['q#1a', 'q#2b'], ['q#1c', 'q#2d'], ['q#1e', 'q#2f']],
findQuote = (quote, quotes) => quotes.includes(quote),
whoSaidIt = c => names[c],
quote = "q#1c";
console.log(`${whoSaidIt(quotes.findIndex(findQuote.bind(null,quote)))} said ${quote}`);
&#13;
如果您可以更改数据结构,那么最好将所有内容放在一起:
const quotes = [
{ name: 'John', quotes: ['q#1a', 'q#2b'] },
{ name: 'Helen', quotes: ['q#1c', 'q#2d'] },
{ name: 'Anna', quotes: ['q#1e', 'q#2f'] }
],
findQuote = (quote, quotes) => quotes.quotes.includes(quote),
quote = "q#1c";
console.log(`${quotes.find(findQuote.bind(null,quote)).name} said ${quote}`);
&#13;
答案 3 :(得分:0)
理想情况下,您的findQuote
函数应返回另一个函数。您将引用传递给findQuote
, 返回findIndex
调用数组中每个元素的函数:
function findQuote(quote) {
return function (el) {
return el === quote;
}
}
然后您可以完成代码:
let names = ['Bob', 'Dave', 'Mavis'];
let quotes = ['q#1c','q#2c','q#3c'];
let whoSaidIt = (names, quotes, quote) => {
const index = quotes.findIndex(findQuote(quote));
return `${names[index]} said ${quote}`;
};
const quote = 'q#1c';
const result = whoSaidIt(names, quotes, quote);
<强> DEMO 强>