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


p5.js TypedDict create()用法及代码示例


p5.j​​s中p5.TypedDict的create()方法用于将给定的键值对或对的集合添加到字典中。键值对是一组相互映射的两个值。可以通过使用该对的关键字部分查询此字典来访问这些值。字典可以存储可以使用字典方法访问的多个键/值对。

用法:

create( key, value )

或者

create( obj )

参数:

  • key:它指定用作要添加到字典的键的字符串。
  • value:它指定用作要添加到字典的值的字符串。
  • obj:它指定包含要添加到字典的键值对的对象。

以下示例说明了p5.js中的create()方法:



范例1:

Javascript

function setup() { 
  createCanvas(550, 300); 
  textSize(16); 
  
  let stringDict = 
      createStringDict("Statue of Unity", "182 m"); 
  text("New string dictionary created " + 
       "with one key", 20, 20); 
  
  let existOne =  
      stringDict.hasKey("Statue of Unity"); 
  text("Dictionary has key " + 
       "'Statue of Unity':" + 
       existOne, 20, 60); 
  
  let existTwo =  
      stringDict.hasKey("Spring Temple Buddha"); 
  text("Dictionary has key " + 
       "'Spring Temple Buddha':" + 
       existTwo, 20, 100); 
  
  let tmpObj = { 
    "Spring Temple Buddha":"128 m", 
    "Ushiku Daibutsu":"100 m", 
    "Great Buddha of Thailand":"92m"
  }; 
  
  // Add the given key to the dictionary 
  // specifying the key and value as an object 
  stringDict.create(tmpObj); 
  text("New keys added with create()", 
       20, 140); 
  
  existTwo =  
    stringDict.hasKey("Spring Temple Buddha"); 
  text("Dictionary has key " + 
       "'Spring Temple Buddha':" + 
       existTwo, 20, 180); 
  
  let existThree = 
      stringDict.hasKey("Ushiku Daibutsu"); 
  text("Dictionary has key " + 
       "'Ushiku Daibutsu':" +  
       existThree, 20, 220); 
}

输出:

范例2:

Javascript

function setup() { 
  createCanvas(550, 300); 
  textSize(16); 
  
  let stringDict = 
      createStringDict('Statue of Unity', 
                       '182 m'); 
  text("New string dictionary " + 
       "created with one key", 20, 20); 
  
  let existOne = 
      stringDict.hasKey('Statue of Unity'); 
  text("Dictionary has key 'Statue of Unity':"
        + existOne, 20, 60); 
  
  let existTwo = 
      stringDict.hasKey('Spring Temple Buddha'); 
  text("Dictionary has key " + 
       "'Spring Temple Buddha':" + 
       existTwo, 20, 100); 
  
  // Add the given key to the dictionary 
  // specifying the key and value 
  stringDict.create('Spring Temple Buddha', 
                    '128 m'); 
  text("New key 'Spring Temple Buddha'" + 
       " added with create()", 20, 140) 
  
  existTwo =  
    stringDict.hasKey('Spring Temple Buddha'); 
  text("Dictionary has key " + 
       "'Spring Temple Buddha':" + 
       existTwo, 20, 180); 
}

输出:

在线编辑: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5.TypedDict/create

相关用法


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