在JavaScript(或库JQuery)中是否可以找到具有给定模式的所有(全局)对象?
例如:
objekt_1
objekt_2 //Javascript objects
function find_objects() {
return ....; //return all objects that start with "object"-prefix
}
答案 0 :(得分:2)
是。如果它们是全局的,则它们存储在window
对象中。然后你只需要过滤它们:
function find_objects() {
var objs = [];
for (var k in window) {
var cVariable = window[k];
if (/^objekt/.test(k) && typeof cVariable === "object") {
objs.push(cVariable);
}
}
return objs;
}
演示:
> function find_objects() {
var objs = [];
for (var k in window) {
if (/^objekt/.test(k) && typeof window[k] === "object") {
objs.push(window[k]);
}
}
return objs;
}
undefined
>find_objects()
[]
>var objekt_1 = {a: 1}
undefined
>find_objects()
[Object]
答案 1 :(得分:1)
是
javascript中的全局变量实际上是窗口对象的元素,因此您可以这样做:
for(var i in window) {
var ret = [];
if(i.substr(0,7) == 'object_') ret.push(i);
return ret;
}
答案 2 :(得分:1)
由于它们是全局变量,它们是全局对象的属性,通过浏览器上的window
变量引用。因此,您可以使用for-in
循环找到它们:
var key;
for (key in window) {
// Examine `key` here, it's a string; if it matches, do
// something with `window[key]`, which is the value for that variable
}