如果我不知道JavaScript中的完整变量名,如何查找变量/数组

问题描述 投票:0回答:1

我正在尝试从站点获取其他信息,并且存在随机定义的变量/数组。像这样:

var firstvar_numbers= "already exist"
var secondvar_numbers= ["a","b","c","d"]

数字是站点给出的随机值。在firefox DOM中,当我写了secondvar_的一半时,它立即发现我想要的是因为只有一个以second开头的变量。我的问题是如何通过了解变量的一部分来获取userscript / javascript中变量的值/数组。如果您不了解该示例:Html

//Variable that I need from server
<div id=variables
<script>
var exists_73647286="hello world"

var array_636353=[62,96,11,28]
</script>
<div>

Javascript

//Code that will get array
alert("exists_"+seconpartofvar())
function seconpartofvar(){your code}

OR

alert(autocomplate.exists_)

在这里,我可以在Firefox控制台中编写alert(exists_),它将推荐自动补全。

javascript userscripts
1个回答
1
投票

由于它是在顶层用var声明的,因此您可以遍历window的属性并找到要查找的startsWith之一:

// Example site code:
var array_636353 = [62, 96, 11, 28];

// Userscript code:
const prop = Object.keys(window).find(key => key.startsWith('array_'));
console.log(prop, window[prop]);
© www.soinside.com 2019 - 2024. All rights reserved.