p5.js中的sort()函数用于对数组元素进行排序。如果数组元素是字符串,则按字母顺序对其进行排序;如果数组元素是整数,则按升序对其进行排序。
用法:
sort(Array, Count)
参数:该函数接受上述和以下描述的两个参数:
- Array:此参数保存要排序的数组元素。
 - Count:它包含需要排序的元素数量。该长度应小于数组的长度。
 
返回值:它返回一个新的排序数组。
以下程序说明了p5.js中的sort()函数:
示例1:本示例使用sort()函数对数组元素进行排序。
function setup() {  
  
    // Creating Canvas size 
    createCanvas(500, 90);  
}  
  
function draw() {  
      
    // Set the background color  
    background(220);  
      
    // Initializing the array 
    let Array = ['IT', 'CSE', 'ECE', 'CIVIL']; 
    
    // Initializing the Count which says 
    // the number of elements to be sorted 
    // from starting 
    let Count = 3; 
    
    // Calling to sort() function. 
    let A = sort(Array, Count); 
      
    // Set the size of text  
    textSize(16);  
      
    // Set the text color  
    fill(color('red'));  
    
    // Getting new sorted array 
    text("New sorted array is : " + A, 50, 30); 
               
} 输出:

示例2:本示例使用sort()函数对数组元素进行排序。
function setup() {  
  
    // Creating Canvas size 
    createCanvas(500, 90);  
}  
  
function draw() {  
      
    // Set the background color  
    background(220);  
      
    // Initializing the array 
    let Array = ['IT', 'CSE', 'ECE', 'CIVIL']; 
    
    // Initializing the Count which says 
    // the number of elements to be sorted 
    // from starting 
    let Count = 4; 
    
    // Calling to sort() function. 
    let A = sort(Array, Count); 
      
    // Set the size of text  
    textSize(16);  
      
    // Set the text color  
    fill(color('red'));  
    
    // Getting new sorted array 
    text("New sorted array is : " + A, 50, 30);            
} 输出:

示例3:本示例使用sort()函数对数组元素进行排序。
function setup() {  
  
    // Creating Canvas size 
    createCanvas(500, 90);  
}  
  
function draw() {  
      
    // Set the background color  
    background(220);  
      
    // Initializing the array 
    let Array = [9, 6, 0, 22, 4, 1, 15]; 
    
    // Initializing the Count which says 
    // the number of elements to be sorted 
    // from starting 
    let Count = 5; 
    
    // Calling to sort() function. 
    let A = sort(Array, Count); 
      
    // Set the size of text  
    textSize(16);  
      
    // Set the text color  
    fill(color('red'));  
    
    // Getting new sorted array 
    text("New sorted array is : " + A, 50, 30); 
               
} 输出:

参考: https://p5js.org/reference/#/p5/sort
相关用法
- PHP sort()用法及代码示例
 - PHP Ds\Vector sort()用法及代码示例
 - PHP Ds\Sequence sort()用法及代码示例
 - PHP Ds\Deque sort()用法及代码示例
 - Node.js sort()用法及代码示例
 - Javascript Array sort()用法及代码示例
 - Javascript Sort()用法及代码示例
 - Javascript typedArray.sort()用法及代码示例
 
注:本文由纯净天空筛选整理自Kanchan_Ray大神的英文原创作品 p5.js | sort() function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
