如何在Javascript中一次打印所有变量?

时间:2014-02-05 16:04:14

标签: javascript

我们如何在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)???

4 个答案:

答案 0 :(得分:2)

数据类型不是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循环迭代并写出来。

答案 1 :(得分:0)

  

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

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

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

  

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

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

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

方法1

根据您最近的评论,这将允许您在创建变量时输出变量,并且还可以按照您当前习惯的方式继续使用变量,而无需进行复杂的数据存储创建。

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();