gpt4 book ai didi

javascript - 将表行索引存储为数组索引

转载 作者:行者123 更新时间:2023-12-02 17:26:07 24 4
gpt4 key购买 nike

有一个简单的功能:

selected_row = []; // global scope

function toggleRowNumber(rowIndex) {
if(selected_row[rowIndex]) selected_row.splice(rowIndex, 1);
else selected_row[rowIndex] = 1;
}

使用

toggleRowNumber(50000); // click the row - write the index
toggleRowNumber(50000); // click the row again - remove the inxed

alert(selected_row.length);

50001好的

令人愉快的功能!

那么有没有一种方法可以直接写入|读取索引而无需任何搜索/循环?如果没有上面描述的这一巨大壮举。

谢谢。

最佳答案

如果我理解正确,您想要存储和索引,您可以在其中检查/设置是否选择某个项目。如果是这种情况,您正在寻找“键-值”数据结构。那么,为什么不使用 map 呢?

var selected_row = {};

function toggleRowNumber(rowIndex) {
if(selected_row[rowIndex]) selected_row[rowIndex] = 0; //or = undefined;
else selected_row[rowIndex] = 1;
}

这更好,因为 HashMap 可以节省您的时间和空间。

  • 空格,因为您没有在向量中存储数百个“未定义”值。
  • 时间,因为在许多情况下,用于访问元素的哈希函数会假装找到正确的位置。

关于javascript - 将表行索引存储为数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17916617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com