當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。