简体   繁体   English

如何使用JavaScript中的循环函数声明变量x1,x2,…,x10?

[英]How do you declare variables x1, x2,…,x10 using a loop function in JavaScript?

I am trying to run the following code in JavaScript to accomplish the following task: declare a series of variables that essentially have the same name but are only different in their suffix, which is an integer, eg x1,x2,x3... and so on. 我试图在JavaScript中运行以下代码以完成以下任务:声明一系列变量,这些变量本质上具有相同的名称,但后缀只是不同,后者是一个整数,例如x1,x2,x3 ...和以此类推。

I am new to JavaScript (in fact, I'm entirely new to the coding world). 我是JavaScript的新手(实际上,我是编码领域的新手)。 The following code is what I thought made logical sense but it doesn't want to execute the way I want it to. 以下代码是我认为具有逻辑意义的代码,但它不想执行我想要的方式。

 for (i = 1; i<11; i++) { var x+i = 'variable'+i; } 

There's something else I wish to do... 我还有其他想做的事...

Say, for example, I made a construct such as the following and then proceeded to create customised objects (student1, student2, student3). 举例来说,我进行了如下构造,然后继续创建自定义对象(student1,student2,student3)。 My end goal is to print out, sequentially, the student's name and a comment on their grade. 我的最终目标是按顺序打印出学生的姓名和他们的成绩评论。 Instead of having to type out the function that would print this out for each student I would like to write a loop that would make this process more efficient. 不必键入将为每个学生打印出来的函数,我想编写一个循环使该过程更有效。 However, trying to do this has proven a bit difficult. 但是,尝试执行此操作已被证明有点困难。 Here is the code: 这是代码:

 var grade = function(grade) { switch (grade) { case "A": " could not do any better. Well done"; break; case "C": " had average performance. There's room to improve."; break; case "F": ", an unfortunate result. Will have to try again next year."; break; default: "."; break; } }; function Student(name, sgrade) { this.name = name; this.grade = sgrade; this.print = function() { console.log(this.name+grade(this.grade)); }; } var student1 = new Student("Candice R.", "A"); var student2 = new Student("Robert K.", "C"); var student3 = new Student("Steven M.", "F"); for (i = 1; i<4; i++) { student+i.print(); } /* student[i].print() also doesn't work */ 

Can someone tell me what logic of JavaScript I am not fully understanding that does not allow the above to execute, and is there another way? 有人可以告诉我我不能完全理解的JavaScript的哪些逻辑不允许上述方法执行,还有其他方法吗?

As jfriend00 says, the piece of javascript that you're looking for is arrays. 正如jfriend00所说,您要查找的javascript片段是数组。

Whenever you find yourself adding numbers to variable names, that should indicate that you could put them in an array. 每当您发现自己在变量名称中添加数字时,就表明您可以将它们放入数组中。

So you could replace this: 因此,您可以替换为:

var student1 = new Student("Candice R.", "A");
var student2 = new Student("Robert K.", "C");
var student3 = new Student("Steven M.", "F");

with this: 有了这个:

var students = [];
students.push(new Student("Candice R.", "A"));
students.push(new Student("Robert K.", "C"));
students.push(new Student("Steven M.", "F"));

Now all three of those students are stored together in the students array. 现在,所有这三个学生都存储在students数组中。 The first student is accessed at students[0] , and your for loop should be able to iterate over them easily. 第一个学生可以通过students[0]访问,并且您的for循环应该能够轻松地对其进行遍历。

There are perhaps better ways to define this array of students, but this is a pretty close translation of your existing code. 也许有更好的方法来定义学生数组,但这是您现有代码的相当接近的翻译。

While you could use an array to store your variables and use numeric indices to access them like this: 虽然可以使用数组存储变量并使用数字索引来访问它们,如下所示:

var students = []; // create an array and add student objects to it
students[0] = new Student("Candice R.", "A");
students[1] = new Student("Robert K.", "C");
students[2] = new Student("Steven M.", "F");

for (i = 0; i < students.length; i++) {
  students[i].print();
}

if you really wanted to use the names "student1", "student2", "student3", you could do something like: 如果您真的想使用名称“ student1”,“ student2”,“ student3”,则可以执行以下操作:

var students = {}; // create an empty object and add students as properties
students["student1"] = new Student("Candice R.", "A");
students["student2"] = new Student("Robert K.", "C");
students["student3"] = new Student("Steven M.", "F");

for (i = 1; i < 4; i++) {
  students["student" + i].print();
}

To answer the question of creating such variables in a loop: 要回答在循环中创建此类变量的问题:

var x = {};
for (i = 1; i < 11; i++) {
  x['x' + i] = 'variable' + i;
}

Another name for variable is "identifier." 变量的另一个名称是“标识符”。 Every programming language one can think of restricts names to a specific combination of characters. 人们可以想到的每种编程语言都将名称限制为特定的字符组合。 For: var x+i; 对于:var x + i;

The interpreter sees this and the declaration is an invalid set of characters for an identifier in JavaScript...because it has + operator. 解释器看到了这一点,并且声明是JavaScript中标识符的无效字符集……因为它具有+运算符。 Common restriction is not starting a variable name with a number. 常见的限制不是以数字开头的变量名。 Restricting to $/_/[AZ] for the first character and then a mix of numbers... 限制为$ / _ / [AZ]的第一个字符,然后是数字的混合...

What you are looking for is to use a data structure such as an array or a hash table. 您正在寻找的是使用数据结构,例如数组或哈希表。

var x ={};
var array = []; 

for (i = 1; i<11; i++) {
    //Add a new object property called x1...x2... to the variable x.
   x["x" + i] = 'variable'+i;
   //Add a new string to the Array
   array.push('variable' + i);
}

//Iterate through the properties of the x object you just created
for(var k in x)
{
  //retrieve the item by using x["x1"]
   console.log(x[k]);
}

for(var i=0; i<array.length; i++)
{
   //Retrieve array item by index (starts with zero)
      console.log(array[i]);
}

Use this and it should be ok: 使用它,应该没问题:

for (i = 1; i<4; i++) {
  window['student'+i].print();
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Javascript 将十进制数格式化为 x10 表示法? - How to format decimal number to x10 notation using Javascript? JavaScript中逗号运算符的用途(x,x1,x2,...,xn) - The purpose of the comma operator in JavaScript (x, x1, x2, …, xn) 如果单击 tr(td (x2) 的 x1),如何访问相同 tr (x1) 的 td (x3) 的值? - How do I access the value of a td (x3) of the same tr (x1), if I click on the tr (x1 of td (x2))? 如何使用JavaScript从地图协调中心获取x1,y1,x2,y2? - how to get x1,y1,x2,y2 from map coords with javascript? 如何使用CSS以x = 50,y = 50为中心旋转直线(x1 = 50,y1 = 50,x2 = 50,y2 = 10)? - How to rotate a line(x1=50,y1=50,x2=50,y2=10) with respect to x=50,y=50 as center using CSS? 如何使用src(裁剪)编辑javascript图像对象的x1 y1 x2 y2 - How can i edit the x1 y1 x2 y2 of javascript image object with an src(cropping) 使图像跳转到屏幕上的随机点,并循环 x10? HTML 和 JavaScript - Make image jump to random spots on screen, and loop x10? HTML and javascript 线的点x1,x2,y1,y2与径向树中的节点不一致 - the lines' points x1, x2, y1, y2 do not coincide with nodes in a radial tree 如何显示裁剪后的图像的(x1,y1,)和(x2,y2) - How to display (x1,y1,) and (x2,y2) of croped image fengyuanchen Cropper:如何获取裁剪后图像的x1,y1,x2,y2坐标 - fengyuanchen Cropper: How to get x1, y1, x2, y2 coordinates of the cropped image
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM