Excel喜欢在javascript中编制索引

Gre*_*egA 2 javascript indexing excel matrix

我编写了一个函数,将excel像索引(A34)转换为JS索引(array [0] [33]).

但是当列名称更复杂时(例如AA),它似乎不起作用.

这是我到目前为止的代码

function excel_index(address) {
  let col = address.charCodeAt(0)-65;
  let row = address.substring(1)-1;
  return this[row][col];
}

Array.prototype.excel = excel_index;
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 5

您可以使用parseInt基数36和9的修正(这只得到字母的值)和值和Array#reduce整数字母.

因子26是字母表的长度,而左边的字母的位置值是26.

function excel_index(address) {
    var col = address.match(/[A-Z]+/)[0],
        row = address.match(/\d+/i)[0];

    return {
        col: col.split('').reduce((r, a) => r * 26 + parseInt(a, 36) - 9, 0) - 1,
        row: row - 1
    };
}

console.log(excel_index('A1'));
console.log(excel_index('AA33'));
console.log(excel_index('ZZ42'));
Run Code Online (Sandbox Code Playgroud)