【问题标题】:How to print all the variable at once in Javascript?如何在Javascript中一次打印所有变量?
【发布时间】:2014-02-05 16:04:13
【问题描述】:

我们如何在 javascript 中一次打印所有变量?例如,考虑以下代码:-

var str1 = "Programming is fun";
var str2 = "Programming is cool";
document.write(str1);
document.write(str2);

在这里,我有两个变量,我写了两次 document.write() 语句。如果我有 1000 个这样的变量,那么我需要编写 document.write() 语句 1000 次吗?如何打印这 1000 个变量? 是否有根据数据类型打印值(在这种情况下,数据类型是var)???

【问题讨论】:

  • 如果你用var 声明它们没有好办法,因为变量要么是本地的,要么是window 的属性。如果将它们声明为对象或数组的属性,则可以使用 for-in 循环。
  • 你可以将它们存储在一个数组中并循环该数组,数据类型也不是var
  • var 不是“数据类型”。
  • @Pietu1998 如果它们是window 的属性,那么为什么不能遍历它们呢?例如stackoverflow.com/questions/2934787/…
  • @gvee 仅当您处于主机环境的全局范围内时。

标签: javascript


【解决方案1】:

数据类型不是var。在 JavaScript 中,var 关键字用于指示您在当前范围内声明了一个新变量,它不会传达有关变量类型的任何信息。

如果要打印出未知数量的变量,请使用数组:

var arr = [];
arr.push("Programming is fun");
arr.push("Programming is cool");

for(var i = 0, l = arr.length; i < l; i++) {
    document.write(arr[i]);
}

您也可以像这样初始化数组:

var arr = ["Programming is fun", "Programming is cool"];

然后使用相同的for 循环遍历并写出它们。

【讨论】:

  • 如果你想让它更短,考虑arr.forEach(document.write.bind(document));
  • 感谢您的回答。但是我想知道我们是否可以根据变量(var)进行打印。如果声明了任何新变量,则必须自动打印它。类似的东西。请帮忙!!
【解决方案2】:

方法一

根据您最近的 cmets,这将让您在创建变量时输出变量,并以您当前习惯的方式继续使用变量,而无需进行复杂的数据存储创建。

Here is a working example, try it out

代码:

// include this function once in your code, at the top of the script, 
// and outside of any other functions. 

function v(value) {
    var outputText = (typeof value === "object" && value.constructor === Object && window.JSON) ? JSON.stringify(value) : value;
    document.body.appendChild(document.createTextNode(outputText));
    document.body.appendChild(document.createElement("br"));
    return value;
}

// When you create variables, use this function to assign and output the value.
// So instead of:   var someVariable = "someValue";
// Use:             var someVariable = v("someValue");
// this will output the value to the document, 
// and still assign the variables as you'd expect. 



// create and output a "greeting" variable
var greeting = v("Hello There!");


// create and output an array of primary colours
var primaries = v(["red", "green", "blue"]); 


// alert the greeting - alerts: "Hello there!"
alert(greeting);

方法 2

这更复杂但也更有用。它创建了一个数据存储对象,该对象既可以为您的变量提供整洁的存储,也可以使用一些方法来设置它们的输出、获取它们以供使用、删除它们并再次输出它们。对你来说可能有点矫枉过正,但写起来很有趣! :)

Here is a working example

代码:

// An object in which to store variables, which also writes variables to a given element as you create them.
// Include this code at the top of your javascript. 

var VariableStore = function(outputElement) {
    this.store = {};
    this.outputElement = outputElement;
};
VariableStore.prototype = {
    create : function(key, value) {
        this.store[key] = value;
        this.output(key);
    },
    get : function(key) {
        return this.store[key];
    },
    destroy : function(key) {
        delete this.store[key];
    },
    output : function(key) {
        var value = this.store[key];        
        var outputText = (typeof value === "object" && value.constructor === Object && window.JSON) ? JSON.stringify(value) : value;
        this.outputElement.appendChild(document.createTextNode(outputText));
        this.outputElement.appendChild(document.createElement("br"));
    },
    outputAll : function() {
        for(var key in this.store) {
            this.output(key);
        }
    }
};


// Here's how to use the object above.

// 1. Create a new instance of VariableStore, here called v. This only needs to be done once in your script, just underneath the VariableStore object above.

var v = new VariableStore(document.body);


// 2. This creates three new variables. They will be automatically outputted to the output element when they are created. This code can go anywhere in your script underneath the first two steps.
// The arguments are: v.create("yourVariableName", "Your Variable Contents");

v.create("myName", "Zougen Moriver"); // a simple String
v.create("primaryColours", ["red", "green", "blue"]); // an array of primary colours
v.create("someObject", {"greeting":"Hi There!"}); // A friendly object literal


// if you need to delete a variable again, this deletes the primaryColours array for example

v.destroy("primaryColours");



// 3. You can retreive any of the variables you create using v.get("variableName"). Here, we retreive the "name" variable we just created and alert it.

alert(v.get("myName"));



// 4. If you want to output all the variables again, use v.outputAll();

v.outputAll();

【讨论】:

  • 感谢您的回答。但是我想知道我们是否可以根据变量(var)进行打印。如果声明了任何新变量,则必须自动打印它。类似的东西。请帮忙!!
  • 这些变量。 var 声明“只能从同一范围内访问以下变量”,除非您的 var 语句在函数内,否则它将是全局 window 对象。请阅读scopes here。在我的示例中,变量被显式创建为不同对象 (store) 的属性。不需要var。这使它们都集中在一个地方。至于自动打印,我很想知道您为什么需要这样做?
  • 我已根据您的最新评论用新想法更新了我的答案。我建议查看选项 1。
  • 非常感谢。这很有帮助。坦率地说,没有什么特别的项目或类似的东西我想实现这个。它刚刚浮现在我的脑海中,我尝试将其编码但失败了。所以我发布了这个qn。非常感谢您的回答。这正是我所需要的。
  • 太棒了。很高兴它对您有所帮助,请务必接受答案,因为它已经回答了您的问题。
【解决方案3】:

如果我有 1000 个这样的变量,那么我是否需要编写 document.write() 语句 1000 次

或者将字符串与+连接在一起。

如果您有多个相关变量,则以编程方式关联它们。将它们放入一个数组(如果它们是连续的)或一个对象(如果它们不是)。然后,您可以遍历该数据结构。

是否有根据数据类型打印值(在这种情况下,数据类型是var)

var 不是数据类型。它是一个设置变量范围的关键字。

typeof 运算符会告诉您数据类型(另请参阅 instanceof),但您仍然需要一种方法将其应用于您要处理的每条数据(所以我们回到数组/对象)。

【讨论】:

  • 感谢您的回答。但是我想知道我们是否可以根据变量(var)进行打印。如果声明了任何新变量,则必须自动打印它。类似的东西。请帮忙!!
  • 不,你不能。这就是为什么您应该以合理的结构组织数据。
【解决方案4】:

您必须创建一个数据结构,很可能是一个数组,用您的变量填充该数组,然后循环并输出它们。像这样的东西。

var myArray = ['programming is fun', 'programming is cool', 'programming is lame'];
for(var i = 0; i < myArray.length; i++){
  document.write(myArray[i]);
}

【讨论】:

  • myArray.forEach(document.write.bind(document));
  • 感谢您的回答。但是我想知道我们是否可以根据变量(var)进行打印。如果声明了任何新变量,则必须自动打印它。类似的东西。请帮忙!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-21
  • 2020-08-01
相关资源
最近更新 更多