for循环,写入两个具有相同索引的数组

时间:2013-02-27 19:12:43

标签: javascript

想知道是否可以按照以下方式做某事:

var label = new Array();
    label[0] = "label0";
    label[1] = "label1";

var value = new Array();
    value[0] = "value0";
    value[1] = "value1";

for (i=0,i<label.length,i++)
    {
        document.write( label[i] + " = " + value[i] );
    }

标签数组显然属于值数组,并且它们的大小始终相同。如果有正确的方法吗?

编辑:这是真正的交易

var documents = new Array();

documents[0] = navigator.appCodeName;
documents[1] = navigator.appMinorVersion;
documents[2] = navigator.appName;
documents[3] = navigator.appVersion;
documents[4] = navigator.browserLanguage;
documents[5] = navigator.buildID;
documents[6] = navigator.cookieEnabled;
documents[7] = navigator.cpuClass;
documents[8] = navigator.language;
documents[9] = navigator.mimeTypes;
documents[10] = navigator.onLine;
documents[11] = navigator.oscpu;
documents[12] = navigator.platform;
documents[13] = navigator.plugins;
documents[14] = navigator.productSub;
documents[15] = navigator.userLanguage;
documents[16] = navigator.userProfile;
documents[17] = navigator.vendor;
documents[18] = navigator.vendorSub;

var label = new Array();

label[0] = "appCodeName";
label[1] = "appMinorVersion";
label[2] = "appName";
label[3] = "appVersion";
label[4] = "browserLanguage";
label[5] = "buildID";
label[6] = "cookieEnabled";
label[7] = "cpuClass";
label[8] = "language";
label[9] = "mimeTypes";
label[10] = "onLine";
label[11] = "oscpu";
label[12] = "platform";
label[13] = "plugins";
label[14] = "productSub";
label[15] = "userLanguage";
label[16] = "userProfile";
label[17] = "vendor";
label[18] = "vendorSub";

for(var i=0;i<documents.length;i++)
    {
        document.write( label[i] + " = " documents[i] + "<br >" );
    }   

错误是: 未捕获的SyntaxError:意外的标识符print.htm:56

3 个答案:

答案 0 :(得分:0)

是的,这样可以正常工作。 i只是一个包含数字的变量 - 但要确保使用var正确声明它,否则它将是全局变量!你还应该使用[](一个空的数组文字)来创建新的空数组,你应该在实践中避免使用document.write(但对于这样的独立练习来说没问题)。

如果你澄清了你想要完成的事情,这也会有所帮助。

答案 1 :(得分:0)

您可以使用一组对象,而不是两个字符串数组。这将确保它们的长度始终相同。

var labelsAndValues = new Array();
    labelsAndValues[0] = { label: "label0", value: "value0" };
    labelsAndValues[1] = { label: "label1", value: "value1" };

for (i=0,i<labelsAndValues.length,i++)
{
    document.write( labelsAndValues[i].label + " = " + labelsAndValues[i].value );
}

答案 2 :(得分:0)

为什么使用两个数组?使用对象来保存带有值的键。

var obj = {
    "appCodeName" : navigator.appCodeName,
    "appMinorVersion":  navigator.appMinorVersion,
    "appName": navigator.appName
}

for (var x in obj) {
    if (obj.hasOwnProperty(x)) {
        console.log(x,"=","obj[x]);
    }
}

如果您要浏览导航器对象,可以循环浏览它。

for( var prop in navigator) {
    console.log(prop,"=",(navigator[prop]||"").toString());
}