我试图在包含多个对象的数组中查找对象的索引。我已经在这方面挣扎了一段时间,并将其简化为您所看到的并且仍然无法获得它。请让我知道什么会起作用,这样我才能得到"输入"对象来自matchBetween("string1");
matchBetween("string1");
matchBetween = function (result) {
let params = [
{ param: "string1", input: "inputstring1"},
{ param: "string2", input: "inputstring2"}
];
console.log(result, params, params.param ); //Output: "string1", (2)[{...}, {...
let location = params.findIndex (x => Object.is(result, x));
console.log(location); //outputs -1
return params[location].input // 'Cannot read property 'input' of undefined'
};
我尝试了多种方法,但我觉得这很容易解决,我只是错过了它。提前谢谢你!
答案 0 :(得分:2)
Object.is(result, x)
错了。
运行params.findIndex (x => {console.log(x); return false;});
以查看每个x的外观
{param: "string1", input: "inputstring1"}
{param: "string2", input: "inputstring2"}
因此,您可以使用Jean提到的Object.is(result, x.param)
,或result === x.param
,或只是
params.find(x => x.param === result).input
注意,您需要在找不到结果时进行处理。
答案 1 :(得分:1)
试试这个样本:
matchBetween = function (result) {
let params = [
{ param: "string1", input: "inputstring1"},
{ param: "string2", input: "inputstring2"}
];
console.log(result, params, params[0].param ); //Output: "string1", (2)[{...}, {...x=>x.param == result
let location = params.findIndex (function(x) { return Object.is(result, x.param); });
console.log(location); //outputs -1
return params[location].input // 'Cannot read property 'input' of undefined'
};
console.log(matchBetween("string2"));