gpt4 book ai didi

javascript - 改进了在 javascript 中构建嵌套唯一值数组的方法

转载 作者:行者123 更新时间:2023-11-30 08:55:51 25 4
gpt4 key购买 nike

设置:

我有一个显示分层数据的嵌套 html 表格结构,用户可以隐藏或显示各个行。每行都有一个 dom id,它由级别编号加上该级别上记录类型的主键组成。我必须两者都有,因为每个级别都来自不同的数据库表,所以主键本身在 dom 中不是唯一的。

example: id="level-1-row-216"

我将可见元素的级别和行存储在 cookie 中,这样当页面重新加载时,用户打开的相同行可以自动显示。我不存储 dom id 的完整映射,因为我担心它变得过于冗长,并且我希望将我的 cookie 保持在 4Kb 以下。

所以我将 dom id 转换为这样一个紧凑的 json 对象,每个级别都有一个属性,每个级别下都有一个唯一的主键数组:

{
1:[231,432,7656],
2:[234,121],
3:[234,2],
4:[222,423],
5:[222]
}

通过将此结构存储在 cookie 中,我将其提供给我的显示函数并在页面加载时恢复用户之前的披露状态。

需要改进的地方:

我正在寻找更好的选择来将我的 id 选择器映射缩减为这种紧凑格式。这是我的功能:

function getVisibleIds(){

// example dom id: level-1-row-216-sub

var ids = $("tr#[id^=level]:visible").map(function() {
return this.id;
});

var levels = {};

for(var i in ids ) {
var id = ids[i];
if (typeof id == 'string'){
if (id.match(/^level/)){

// here we extract the number for level and row
var level = id.replace(/.*(level-)(\d*)(.*)/, '$2');
var row = id.replace(/.*(row-)(\d*)(.*)/, '$2');

// *** Improvement here? ***
// This works, but it seems klugy. In PHP it's one line (see below):

if(levels.hasOwnProperty(level)){
if($.inArray(parseInt(row, 10) ,levels[level]) == -1){
levels[level].push(parseInt(row, 10));
}
} else {
levels[level] = [parseInt(row, 10)];
}

}
}
}

return levels;
}

如果我用 PHP 来做,我会像这样构建紧凑​​数组,但我无法在 javascript 中弄明白:

foreach($ids as $id) {
if (/* the criteria */){
$level = /* extract it from $id */;
$row = /* extract it from $id */;
$levels[$level][$row];
}
}

最佳答案

所以你的函数中有一些重复的/不需要的东西:

如果你这样做

var ids = $("tr#[id^=level]:visible").map(function() {

还有这个

for(var i in ids ) { 

你在匹配的 id 上循环了两次

这里的 id 不是一直是字符串吗???

if (typeof id == 'string'){

这不是必需的,因为你的 jQuery-Selector: "tr#[id^=level]:visible"您的匹配元素应始终以“level”开头

if (id.match(/^level/)){

总而言之,我认为这应该更短(无法测试,下次请提供一个 jsfiddle,会更容易 ;-))

function getVisibleIds(){

// example dom id: level-1-row-216-sub
var level, parsed, levels = {};

$("tr#[id^=level]:visible").map(function() {
// here we extract the number for level and row
level = this.id.replace(/.*(level-)(\d*)(.*)/, '$2');
parsed = parseInt(this.id.replace(/.*(row-)(\d*)(.*)/, '$2'), 10);

// i like this more
if(!levels.hasOwnProperty(level)) { levels[level] = []; }
if($.inArray(parsed, levels[level]) === -1) {
levels[level].push(parsed);
}
});

return levels;
}

关于javascript - 改进了在 javascript 中构建嵌套唯一值数组的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13623869/

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