# arr.indexDictionaryForValues()

[JS](/web/js.md) ⟩ [objects](/web/js/val/obj.md) ⟩ [Array](/web/js/val/builtin/arr.md) ⟩ [methods](/web/js/val/builtin/arr/method.md) ⟩ indexDictionaryForValues()

{% hint style="success" %}
主要用於找 [Google Sheet](/web/appendix/gas/google-sheet.md) 的<mark style="color:yellow;">**欄位索引**</mark> (column index)。
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: [replit](https://replit.com/@pegasusroe/arrayindexOfValues#index.js)

```javascript
/* 
 * 🔸 array.indexDictionaryForValues(values)
 * return the index for each value (a dictionary object)
 *
 * @example
 *
 *   let row = ["座號", "姓名", "國語文", "英語文"];
 *   row.indexDictionaryForValues(["座號", "姓名"]) // { '座號': 0, '姓名': 1 }
 */
Array.prototype.indexDictionaryForValues = function(values){
    
    let dict = {};
    
    for(const value of values){
        const i = this.indexOf(value);
        if(i < 0) throw new Error(`⛔ array.indexDictionaryForValues(): array doesn't have value "${value}"`);
        dict[value] = i;
    }
    
    return dict;
};
```

💈範例：

```javascript
let array = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
let row = ["座號", "姓名", "國語文", "英語文"];

array.indexDictionaryForValues([777, 22])        // { '22': 2, '777': 5 }
row.indexDictionaryForValues(["座號", "姓名"])    // { '座號': 0, '姓名': 1 }
// row.indexDictionaryForValues(["沒這個值"])     // ⛔ Error
```

{% endtab %}

{% tab title="⬇️ 應用" %}

* [各班平均及前三名](/web/appendix/gas/projects/class-average.md) - 用於找欄位索引 (column index)
* [國中成績一覽表](/web/appendix/gas/projects/guo-zhong-cheng-ji-yi-lan-biao.md)
* [Google Apps Script](/web/appendix/gas.md) app [helpers](/web/appendix/gas/app/helpers.md).
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/js/val/builtin/arr/ext/arr.indexdictionaryforvalues.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
