public class Animal { // 接受可變參數的方法 void eat(String... Objects) { for (String x : Objects) { System.out.println("我吃了一個" + x + "!"); } } // 調用示例 public static void main(String[] args) { Animal dada = new Animal(); dada.eat("蘋果", "南瓜餅", "土豆"); } /* outputs: 我吃了一個蘋果! 我吃了一個南瓜餅! 我吃了一個土豆! */ }
>>> def f(*args, **kw): ... print(args) ... print(kw) ... >>> f(1, 2, 3, name = 'dada', age = 5) (1, 2, 3) {'age': 5, 'name': 'dada'}
能夠理解爲將位置參數收集爲一個叫作args的tuple,將關鍵字參數收集爲一個叫作kw的dict。c++
PS. 位置參數、關鍵字參數應該是Python特有的...app
#include <iostream> #include <initializer_list> using namespace std; int sum(initializer_list<int> il) { int sum = 0; for (auto &x : il) { sum += x; } return sum; } int main() { cout << sum({1, 2, 3, 4, 5}) << endl; // output=15 return 0; }
const ilike = (...foods) => { for (let x of foods) { console.log(`i like eat ${x}`); } };
ilike('apple', 'chicken'); => i like eat apple => i like eat chicken
PS. 請忽略語法錯誤...blog
三點號還能這麼用:索引
let words = ["never", "fully"]; console.log(["will", ...words, "understand"]); // → ["will", "never", "fully", "understand"]