javascript 使用 url 作为数组的字符串

javascript use url as string for array

我有一个带数组的外部 .js。

test = [
{
    "name": "1"
}
test2 = [
{
    "name": "2"
}
];

现在我想用url来识别数组的名字。 因此,如果有人继续 test.html 他正在使用测试数组和 test2.html test2 数组。

如果我用

var queryArray = window.location.search.substring(1);

var queryArray = window.location.href

或类似的东西然后

document.getElementById("demo").innerHTML = queryArray.name;

不行,因为他当然是在找queryArray这个不存在的数组。 有没有办法使用 url 作为标识符?

希望大家能看懂点^^

感谢每一个想法!!!

如果您能够稍微调整指定 "arrays" 的方式,您可以这样做:

// =============================
// Similar but a little more tidy
// This also supports file names with characters like "-" or complete url strings
// =============================
var dataItems = [
  {key : "test1", value: [{"name": "This is test 1"}]},
  {key : "test2", value: [{"name": "This is test 2"}]},
  {key : "js", value: [{"name": "This is the sandbox"}]} // This sandbox (I think)
];
// =============================

// =============================
// You migth now use the full pathname as the data item key,
// but if you wanted to use the "name" of the file you might do something like this.
// =============================
var currentFileName = location.pathname.split("/").pop().split(".html")[0];
// =============================

// =============================
// You might want to do this in several steps to handle stuff like filter returning
// no hits.
// =============================
var dataItem = dataItems.filter(function(item){ return item.key === currentFileName;})[0];
// =============================

console.log(dataItem.value[0].name);