[英]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.