当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Processing Array用法及代码示例


Processing, 类Array用法介绍。

构造函数

  • datatype[] var
  • var[element] = value
  • var.length

参数

  • datatype 任何原始或复合数据类型,包括用户定义的类
  • var 任何有效的变量名
  • element int:不能超过数组的长度减1
  • value 分配给数组元素的数据;必须与数组的数据类型相同

说明

数组是数据的列表。可以有任何类型的数据的数组。数组中的每条数据都由一个索引号标识,该索引号表示它在数组中的位置。数组中的第一个元素是 [0] ,第二个元素是 [1] ,依此类推。数组类似于对象,因此必须使用关键字 new 创建它们。



每个数组都有一个变量 length ,它是数组中元素总数的整数值。请注意,由于索引编号从零(而不是 1)开始,因此 length 为 5 的数组中的最后一个值应引用为 array[4](即 length 减 1),而不是 array[5] ,这会触发错误。



另一个常见的混淆来源是使用 length 获取数组的大小和使用 length() 获取字符串的大小之间的区别。注意使用字符串时括号的存在。 (array.length 是一个变量,而String.length() 是一个特定于 String 类的方法。)

例子

int[] numbers = new int[3];
numbers[0] = 90;  // Assign value to first element in the array
numbers[1] = 150; // Assign value to second element in the array
numbers[2] = 30;  // Assign value to third element in the array
int a = numbers[0] + numbers[1]; // Sets variable 'a' to 240
int b = numbers[1] + numbers[2]; // Sets variable 'b' to 180 
int[] numbers = { 90, 150, 30 };  // Alternate syntax
int a = numbers[0] + numbers[1];  // Sets variable 'a' to 240
int b = numbers[1] + numbers[2];  // Sets variable 'b' to 180
int degrees = 360;
float[] cos_vals = new float[degrees];
// Use a for() loop to quickly iterate
// through all values in an array.
for (int i=0; i < degrees; i++) {         
  cos_vals[i] = cos(TWO_PI/degrees * i);
}
float[] randoms = new float[100];
for (int i = 0; i < randoms.length; i++) {
  randoms[i] = random(100);
}

// You can also use an enhanced loop
// to access the elements of an array
for (float val : randoms) {
  println(val);
}

// This works with arrays of objects, too,
// but not when first making the array
PVector[] vectors = new PVector[5];
for (int i = 0; i < vectors.length; i++) {
  vectors[i] = new PVector();
}

// The syntax only applies when iterating
// over an existing array 
for (PVector v : vectors) {
  point(v.x, v.y);
}

相关用法


注:本文由纯净天空筛选整理自processing.org大神的英文原创作品 Array。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。