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


p5.js NumberDict div()用法及代码示例


p5.j​​s中p5.NumberDict的div()方法将给定键上的值除以给定值,并将更新后的结果存储在同一键上。键值对是一组相互映射的两个值。可以通过使用该对的关键字部分查询此字典来访问这些值。数字字典可以存储可以使用字典方法访问的多个键-值对。

用法:

div( Key, Amount )

参数:该函数有两个参数,如上所示和以下讨论:

  • Key:这是一个数字,表示将从中分割值的键。
  • Amount:这表示将数值除以的数字,

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

例:



Javascript

let y = 0; 
  
function setup() { 
  createCanvas(550, 500); 
  textSize(16); 
  
  text("Click on the button to create a new " + 
       "dictionary and divide the given value", 
       20, 20); 
  
  text("Key:", 20, 260); 
  text("Value:", 160, 260); 
  
  key_input = createInput(); 
  key_input.position(70, 250); 
  key_input.size(40); 
  
  val_input = createInput(); 
  val_input.position(220, 250); 
  val_input.size(40); 
  
  setBtn =  
    createButton("Create random dictionary"); 
  setBtn.position(30, 40); 
  setBtn.mouseClicked(createNewDict); 
  
  divBtn = 
    createButton("Divide given value at key"); 
  divBtn.position(30, 300); 
  divBtn.mouseClicked(divVal); 
} 
  
function createNewDict() { 
  clear(); 
  
  // Create an object with random values 
  let obj = {}; 
  for (let i = 0; i < 6; i++) { 
    let rk = ceil(Math.random() * 100); 
    let rn = floor(Math.random() * 100); 
    obj[rk] = rn; 
  
    text("Key:" + rk + ":Value:" + 
         rn, 40, 120 + 20 * i); 
  } 
  
  // Create a number dict using the above values 
  numDict = createNumberDict(obj); 
  
  text("New Dictionary created with values", 
       20, 80); 
  
  text("Click on the button to create a new " + 
       "dictionary and divide the given value", 
       20, 20); 
  
  text("Key:", 20, 260); 
  text("Value:", 160, 260); 
} 
  
function divVal() { 
    
  // Get the key and value to be updated 
  let keyToChange = int(key_input.value()); 
  let valToDiv = int(val_input.value()); 
  
  // Get the previous value in the dictionary 
  let prevVal = numDict.get(keyToChange); 
  
  // If the key exists in the dictionary 
  if (prevVal) { 
    numDict.div(keyToChange, valToDiv); 
  
    // Get the updated value 
    let updatedVal = numDict.get(keyToChange); 
    
    text("The value at key:" + keyToChange + 
         " was:" + prevVal, 20, 360 + y * 40); 
    text("The updated value at key:" + 
         keyToChange + " is:" + updatedVal, 
         20, 380 + y * 40); 
  } 
  else { 
    text("Please enter a proper key", 
         20, 380 + y * 40); 
  } 
  
  y = y + 1; 
  
  text("Click on the button to create a new " + 
       "dictionary and divide the given value", 
       20, 20); 
}

输出:

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

相关用法


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