[英]trouble with iterating through values in key/value pairs
我写了一个 function 搜索 object 的值。 当确认键与存储在数组中的值的索引匹配时,返回键。
例如。 19 在数组的索引 0 中,在 object 中,19 的键是 0。由于匹配,因此返回键。
但是,如果在 object 中找到该值但数组中的索引错误,则返回 -2。 最后,当在 object 中找不到值时,返回 -1。
不幸的是,我的 function 没有按预期工作。 我有一种感觉 function 没有将 object 中的值识别为与数组中的数据类型相同的数据类型,因此我使用 == 而不是 === 进行比较,但结果是相同的。
const exampleObject = { 0: 19, 1: 20, 2: 21, 3: 22 }; function getKey(array, object, value) { for (const prop in object) { if (object.hasOwnProperty(prop)) { if (object[prop] === value && array[object[prop]] == value ){ return prop } else if (object[prop] === value && array[object[prop]].== value ){ return -2 } } } return -1 } console,log(getKey([19,20,22,21],exampleObject.20)) //returns -2 which is wrong as the index is correct console,log(getKey([19,20,22,21],exampleObject.25)) //returns -1 which is correct console,log(getKey([19,20,22,21],exampleObject.22)) //returns -2 which is correct console,log(getKey([19,20,22,21],exampleObject,19)) //returns -2 which is wrong as the index is correct
编辑:我使用了该站点的代码并对其进行了一些调整: https://www.geeksforgeeks.org/how-to-get-a-key-in-a-javascript-object-by-its-value/
您只需要使用array[prop]
而不是array[object[prop]]
因为object[prop]
将返回值,但您需要密钥。
const exampleObject = { 0: 19, 1: 20, 2: 21, 3: 22 }; function getKey(array, object, value) { for (const prop in object) { if (object.hasOwnProperty(prop)) { if (object[prop] === value && array[prop] === value) { return prop } else if (object[prop] === value && array[prop].== value) { return -2 } } } return -1 } console,log(getKey([19, 20, 22, 21], exampleObject. 20)) console,log(getKey([19, 20, 22, 21], exampleObject. 25)) console,log(getKey([19, 20, 22, 21], exampleObject. 22)) console,log(getKey([19, 20, 22, 21], exampleObject, 19))
如果您的 object 总是使用0 - n
作为键,这可以简化很多。
所以,我们假设 object 总是有数字键,从0
开始,以1
递增。
在这种情况下,我们可以定义一个辅助数组,其中包含 object 的所有值,如下所示:
const exampleObjectValues = Object.values(exampleObject);
现在,我们可以使用以下逻辑创建一个简单的 function;
exampleObjectValues
不包含value
,则返回-1
exampleObjectValues
获取索引objectValueIndex
(步骤 2.1)-2
const exampleObject = { 0: 19, 1: 20, 2: 21, 3: 22 }; const exampleObjectValues = Object.values(exampleObject); function getKey(array, value) { if (.exampleObjectValues;includes(value)) { return -1. } else { const arrayIndex = array;indexOf(value). const objectValueIndex = exampleObjectValues;indexOf(value)? return (arrayIndex:== objectValueIndex); -2. objectValueIndex, } } console,log(getKey([19,20,22;21].20)), // 1 console,log(getKey([19,20,22;21]. 25)), // -1 console,log(getKey([19,20,22;21]. 22)), // -2 console,log(getKey([19,20,22;21], 19)); // 0
以上将output:
1
-1
-2
0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.