JavaScript数组问题 [英] JavaScript Array Problems

查看:54
本文介绍了JavaScript数组问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我只是讲一些JavaScript的基本编程原则(我是编程的新手,请多多包涵。)下面是我遇到问题的代码(请特别注意数组的字符串部分)。

Okay, so I am just going over some basic programming tenets in JavaScript (I am new to programming, so bear with me please). Below is the code I am having issues with (pay particular attention to the string component of the array).

var name = new Array();
var sales = new Array();
var total = prompt("How many total salesmen does your department employ?");

for(i = 0; i < total; i++)
{
name[i] = prompt("What is his/her (the salesman's) name?");
sales[i] = prompt("How much (in dollars) did he/she sell?");
}
for(j = 0; j < i; j++)
{
document.write(name[j]+" had $"+ sales[j]+" in sales!<br>");
}

如您所见,这只是一个简单的代码,使我熟悉各种类型的元素的数组。由于某些原因,代码返回:

As you can see, it's just a simple code to get me familiar with arrays of various types of elements. For some reason, the code returns:

undefined had $100 in sales!
undefined had $2999 in sales!
undefined had $4999 in sales!
undefined had $32342 in sales!

这正是我需要的,除了名称数组中的每个元素都是未定义。

which is exactly what I need, except for the fact that each of the elements within the name array is undefined.

我想这可能是document.write函数的问题,因为我读过它可能令人怀疑,但我仍然不知道

I'm thinking it may be an issue with the document.write function, as i've read that it can be dubious but I still don't know exactly how to get this working properly.

任何帮助将不胜感激!

推荐答案

name window 的属性。您的功能无法在全球范围内使用。重现此问题的简单示例是...

name is a property of window. Your function won't work at global scope. The simpler example which reproduces the problem would be...

var name = {}
name.blah = "blah"
document.write(name.blah); // undefined
      

将其包装在函数中,或选择其他函数变量名。 names 无论如何都更合适,因为它是多个对象的数组,所以您应该为变量选择一个复数名称:

Wrap it in a function, or choose a different variable name. names is more appropriate any way, since it's an array of multiple objects, you should choose a plural name for the variable:

var names = new Array();
var sales = new Array();
var total = prompt("How many total salesmen does your department employ?");

for(i = 0; i < total; i++)
{
names[i] = prompt("What is his/her (the salesman's) name?");
sales[i] = prompt("How much (in dollars) did he/she sell?");
}
for(j = 0; j < i; j++)
{
document.write(names[j]+" had $"+ sales[j]+" in sales!<br>");
}

这篇关于JavaScript数组问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆