gpt4 book ai didi

具有可变维度的 JavaScript 函数数组

转载 作者:行者123 更新时间:2023-11-30 05:34:41 25 4
gpt4 key购买 nike

我正在编写一个函数,它在更多维度上索引一维数组。用户可以选择索引的深度。

例如。

var store = ["Alaska", "Alabama", "North Korea", "South Korea"];

用户可以选择例如深度1。这意味着它将以字符串的第一个字符作为索引

index["a"] = ["Alaska", "Alabama"];
index["n"] = ["North Korea"];

如果用户选择 depth = 2 则它将是索引为两个开始字符的二维数组

index["a"]["l"] = ["Alaska", "Alabama"];

等等

我如何在 JavaScript 中完成一个可以填充变量维度数组的函数?

var indexthis = function(store,depth)
{
if(depth == "undefined")
{depth =1;}
//any Suggestions to go on?
};

问候

最佳答案

这个函数:

function indexWord(index, word, letters) {
var letter;
if (!letters) letters = word.split("");
while (letters.length) {
letter = letters.shift().toLowerCase();
if (!(letter in index)) index[letter] = {_items: []};
index[letter]._items.push(word);
indexWord(index[letter], word, letters);
}
}

这样调用:

var store = ["Alaska", "Alabama", "North Korea", "South Korea"],
index = {}, i;

for (i = 0; i < store.length; i++) {
indexWord(index, store[i]);
}

为您提供以下索引:

{
a: {
_items: ["Alaska", "Alabama"],
l: {
_items: ["Alaska", "Alabama"],
a: {
_items: ["Alaska", "Alabama"],
s: {
_items: ["Alaska"],
k: {
_items: ["Alaska"],
a: {
_items: ["Alaska"]
}
}
},
b: {
_items: ["Alabama"],
a: {
_items: ["Alabama"],
m: {
_items: ["Alabama"],
a: {
_items: ["Alabama"]
}
}
}
}
}
}
},
n: {
_items: ["North Korea"],
o: {
_items: ["North Korea"],
r: {
_items: ["North Korea"],
t: {
_items: ["North Korea"],
h: {
_items: ["North Korea"],
" ": {
_items: ["North Korea"],
k: {
_items: ["North Korea"],
o: {
_items: ["North Korea"],
r: {
_items: ["North Korea"],
e: {
_items: ["North Korea"],
a: {
_items: ["North Korea"]
}
}
}
}
}
}
}
}
}
}
},
s: {
_items: ["South Korea"],
o: {
_items: ["South Korea"],
u: {
_items: ["South Korea"],
t: {
_items: ["South Korea"],
h: {
_items: ["South Korea"],
" ": {
_items: ["South Korea"],
k: {
_items: ["South Korea"],
o: {
_items: ["South Korea"],
r: {
_items: ["South Korea"],
e: {
_items: ["South Korea"],
a: {
_items: ["South Korea"]
}
}
}
}
}
}
}
}
}
}
}
}

其中 index["a"]["l"]._itemsindex.a.l._items 可用于访问 ["Alaska", “阿拉巴马州”]

关于具有可变维度的 JavaScript 函数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24654432/

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