Javascript遍历变量

时间:2018-07-30 17:10:34

标签: javascript html css loops for-loop

所以现在这是我当前的代码,我试图找到一种方法来遍历已经声明的变量(假设变量1-9已经有值)。我只是想知道这是否完全可能?

var title;
var brief;
var hover;
var whatTitle;
var whatDesc;
var whyTitle;
var whyDesc;
var funTitle;
var funDesc;
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
var whyTitles = [];
var whyDescs = [];
var funTitles = [];
var funDescs = [];

    var obj = {'titles' : title};
    if(localStorage.getItem('titles') != null) {
        var tmp = JSON.parse(localStorage.getItem('titles'));
        for(var i = 0;i<tmp.length;i++) {
            titles.push(tmp[i]);
        }

    }
    titles.push(obj);
    localStorage.setItem("titles", JSON.stringify(titles));

如果我们打印出循环代码,则需要输出:

var obj = {'titles' : title};
    if(localStorage.getItem('titles') != null) {
        var tmp = JSON.parse(localStorage.getItem('titles'));
        for(var i = 0;i<tmp.length;i++) {
            titles.push(tmp[i]);
        }

    }
    titles.push(obj);
    localStorage.setItem("titles", JSON.stringify(titles));

var obj = {'briefs' : brief};
    if(localStorage.getItem('briefs') != null) {
        var tmp1 = JSON.parse(localStorage.getItem('briefs'));
        for(var i = 0;i<tmp.length;i++) {
            briefs.push(tmp[i]);
        }

    }
    briefs.push(obj);
    localStorage.setItem("briefs", JSON.stringify(briefs));

var obj = {'hovers' : hover};
    if(localStorage.getItem('hovers') != null) {
        var tmp2 = JSON.parse(localStorage.getItem('hovers'));
        for(var i = 0;i<tmp.length;i++) {
            hovers.push(tmp[i]);
        }

    }
    hovers.push(obj);
    localStorage.setItem("hovers", JSON.stringify(hovers));

...etc

3 个答案:

答案 0 :(得分:1)

如果代码在浏览器中运行,则可以执行以下操作:

for(key in window) { console.log(window[key]) } // print all variables

变量与全局名称空间关联。也就是说,最上方的“ this”引用或窗口对象。

答案 1 :(得分:1)

您几乎拥有了所拥有的代码。如果查看“所需输出”示例,则会发现“展开循环”的每个元素之间唯一真正不同的地方是本地存储的键(“标题”,“摘要”,“悬停”)

请记住,您可以使用对象将键映射到顶层的变量。所以这个:

var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
...

成为( UPDATE :保留初始值设定值):

var key_to_collection = {
  'titles': [title],
  'briefs': [brief],
  'hovers': [hovers],
  'whatTitles': [whatTitles],
  'whatDescs': [whatDescs],
}

然后,您遍历此对象的值:

Object.keys(key_to_collection).forEach(function(key) {
  var obj = {};
  collection = key_to_collection[key];
  obj[key] = collection;
  if(localStorage.getItem(key) != null) {
    var tmp = JSON.parse(localStorage.getItem(key));
    for(var i = 0;i<tmp.length;i++) {
      collection.push(tmp[i]);
    }
  }
  collection.push(obj);
  localStorage.setItem(key, JSON.stringify(collection));
});

答案 2 :(得分:0)

例如,如果您的变量名是title,则可以使用window['title']访问它。这意味着如果您定义了一个全局变量名称数组:

const varNames = ['title', 'brief', 'hover', ...]

然后您可以进行如下循环

for(const name of varNames) {
  const value = window[name]
  // do whatever you want using the variable name and value 
}

我希望这可以解决您的问题:)