簡體   English   中英

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

[英]How to print all the variable at once in 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)???

數據類型不是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循環迭代並寫出來。

如果我有1000個這樣的變量,那么我需要寫1000次document.write()語句

或者將字符串與+連接起來。

如果您有多個相關變量,則以編程方式它們關聯起來。 將它們放在一個數組(如果它們是順序的)或一個對象(如果它們不是)。 然后,您可以遍歷該數據結構。

無論如何根據數據類型打印值(在這種情況下,數據類型是var)

var不是數據類型。 它是一個設置變量范圍的關鍵字。

typeof運算符將告訴您數據類型(另請參見instanceof ),但您仍然需要一種方法將其應用於您想要處理的每個數據(因此我們返回到數組/對象)。

你必須創建一個數據結構,很可能是一個數組,用你的變量填充該數組,然后循環並輸出它們。 像這樣的東西。

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

方法1

根據您最近的注釋,這將允許您在創建變量時輸出變量,並且還可以按照您當前使用的方式繼續使用變量,而無需進入復雜的數據存儲創建。

這是一個有效的例子,試一試

編碼:

// 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

這更復雜但也更有用。 它創建了一個數據存儲對象,它既為變量提供了整齊的存儲,又有一些方法可以使用輸出設置它們,讓它們使用,刪除它們並再次輸出它們。 對你來說可能有點矯枉過正,但寫起來很有趣! :)

這是一個有效的例子

編碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM