> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/builtin/arr/ext/arr.indexdictionaryforvalues.md).

# 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 %}
