首页 > 解决方案 > 使用 JavaScript 中来自多个外部 js 文件的不同数组连接相同的变量

问题描述

我制作了一个离线网络应用程序:

<!DOCTYPE html>
<html dir="rtl">
<head>
<meta charset="utf-8">
<style><!-- some style here --></style>
<script>
var rqid = location.hash.replace('#','');
var js = Math.ceil(rqid / 100);
var id = rqid - ((js - 1) * 100) - 1;
var tg = document.createElement('script')
tg.src = js + '.js'
tg.type = 'text/javascript'
document.head.appendChild(tg);
window.onload = function load() {
var body='<h1>' + title[id] + '</h1> <article>' + content[id] + '</article>';
document.getElementById("body").innerHTML = body;}
</script>
</head>
<body id='body'>
</body>
</html>

上面是简化的article.html文件,它显示了存储在外部 .js 文件中的文章,每个文件都有两个变量。

1.js包含

title = ['title of article1','title of article2',...,'title of article100'];
content = ['content of article1','content of article2',...,'content of article100'];

2.js包含

title = ['title of article101','title of article102',...,'title of article200'];
content = ['content of article101','content of article102',...,'content of article200'];

例如,article.html#1加载1.js到 html 中,然后显示article1,然后article.html#101加载2.js和显示article101

它工作正常,但是我为此应用程序编写的搜索引擎有问题。搜索引擎代码非常庞大。在这里分享它是不可能的。

问题是 .js 文件中的相同变量,它们被一个接一个地覆盖。

<script src="1.js"></script>
<script src="2.js"></script>
<script src="3.js"></script>

因此,搜索仅在3.js.

问题是:是否可以在这些 .js 文件中动态加入标题/内容数组,并具有如下统一的标题/内容变量,因此可以在所有文章中执行搜索?

title = ['title of article1',...,'title of article200'];
content = ['content of article1',...,'content of article200'];

如果不可能,简单地说不,请不要建议重构存储的数据。

我要补充一点,速度/性能不是问题,以防它会变慢。

标签: javascript

解决方案


这是一个简单的示例,说明如何在无需重组1.js..2.js

出于本示例的目的,我创建了一个假装 fetch,它可以获取1.js, & 2.js,如果您有任何真实的 URL 进行测试,我们应该能够将 fetch 模拟替换为真实的。

const pretenddata = {
  "1.js":
  `title = ['title of article1','title of article2','title of article100'];
content = ['content of article1','content of article2','content of article100']`,
  "2.js": `title = ['title of article101','title of article102','title of article200'];
content = ['content of article101','content of article102','content of article200'];`
};

//lets create a pretend fetch..
function fetch(url) {
  function astext() {
    return new Promise((resolve) => {
      resolve(pretenddata[url]);
    });
  }
  return new Promise((resolve) => {
    resolve({text: astext});
  });
}

async function test() {
  var combined_title = [];
  var combined_content = [];
  async function getData(url) {
    const r = await(await fetch(url)).text();
    var d = new Function(`${r}; return [title, content]`)(); 
    combined_title = combined_title.concat(d[0]);
    combined_content = combined_content.concat(d[1]);
  }
  await Promise.all([
    getData("1.js"),
    getData("2.js")
  ]);
  console.log(combined_title);
  console.log(combined_content);
}

test();


推荐阅读