1
votes

Créer un tableau d'objets avec des actions de fonction

Est-il possible de créer un tableau d'objets qui exécutent une fonction? Par exemple, comme ceci:

<script>
console.clear();

const acts = [
  { 'inc' : (x) => x+1 },
  { 'dec' : (x) => x-1 } 
];

console.log(acts.inc(10));
console.log(acts.dec(15));

</script>

Ce qui précède donne une erreur - TypeError: acts.inc n'est pas une fonction.


0 commentaires

3 Réponses :


0
votes

Vous pouvez ajouter une fonction au prototype de tableau.

Array.prototype.inc =


1 commentaires

Cela fonctionnera, mais ne répondra pas tout à fait à la question que j'ai posée. Utilisera en dernier recours. J'essaie de mieux comprendre les opérations sur les objets.



2
votes

Vous y êtes presque! Créez un objet avec des "propriétés de fonction" au lieu d'un tableau d'objets:

acts[0].inc(3)

Ensuite,

4

retournera:

acts.inc(3)

Dans votre code d'origine, vous devrez utiliser:

acts = {
  'inc' : (x) => x+1,
  'dec' : (x) => x-1
};

car c'est un tableau ...


0 commentaires

0
votes

Pour toute personne intéressée, voici comment j'ai utilisé la solution choisie avec un exemple de sortie pour chaque fonction créée (avec quelques options).

    <!DOCTYPE html><html lang="en"><head>
<title> Array of Object Functions </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!-- From: https://stackoverflow.com/questions/62824415/create-array-of-objects-with-function-actions -->
<style>
 body { font-size: 1.2em; line-height: 1.6; }
</style>
</head><body>
<pre id='demo'></pre>

<script>
console.clear();
// following used only for screen display testing purposes
var former = console.log;  // retain former actions of console.log
var demo=document.getElementById('demo');
console.log = function(...msg){
  former(...msg);  // maintains existing logging via the console. (optional)
  demo.append(msg.join(' ')+'\n');  // output needs to be specified
} 
// end of display testing (also shows on console.log display)


const acts = {
  'inc' : (x) => x+1,
  'dec' : (x) => x-1,
  'mul' : (x,y) => x*y,
  'div' : (x,y) => x/y,                      // careful with y=0 (no checks here)
  'pwr' : (x,y) => x**y,                     // x to power of y

  'deg' : (rad) => (rad * Math.PI / 360),    // degrees from radians
  'rad' : (deg) => (deg / Math.PI * 360),    // radians from degrees
  'pct' : (amt) => amt * 100,                // form percentage

  'bit' : (siz) => (acts.pwr(2,siz)-1).toString(2),    // form bit-mask
  'oct' : (dec) => dec.toString(8),                    // form octal
  'hex' : (dec) => dec.toString(16),                   // form hexidecimal

  'fmt' : (amt,size) => amt.toFixed(size),             // number .toFixed(#) string
  'cdt' : (dateInfo,locn='en-US') => dateInfo.toLocaleDateString(locn),   // format US Date object
};

console.log(acts.inc(10));                  // 11
console.log(acts.dec(15));                  // 14
console.log(acts.mul(4,5));                 // 20
console.log(acts.div(5,4));                 // 1.25
console.log(acts.pwr(2,16));                // 65536

console.log(acts.deg(360));                 // 3.14159...
console.log(acts.rad(Math.PI/2));           // 1.57079...
console.log(`${acts.pct(0.15)}%`);          // 15%
console.log(`${acts.pct(acts.div(7,8))}%`); // 87.5%

console.log('0b'+acts.bit(8));              // 0b11111111
console.log('10.0 = 0o'+acts.oct(10),'octal');   // 0o12
console.log('0x'+acts.hex(65535));          // 0xffff

console.log(acts.fmt(Math.PI,2));           // 3.14
console.log(acts.fmt(Math.PI,4));           // 3.1416
console.log(Math.PI);                       // full precision PI

console.log('m/d/yyyy   : ',acts.cdt(new Date()));            // current date (m/d/year format)  US
console.log('dd/mm/yyyy : ',acts.cdt(new Date(),'en-GB'));  // date (dd/mm/year format)  GB


// tests of binary range displays
console.log('\n ','----+'.repeat(6)+'--');
console.log('0b'+acts.bit(0));      // 0b0
console.log('0b'+acts.bit(0).padStart(8,'0'));     // 0b00000000
console.log('0b'+acts.bit(16));             // 0b1111...1111    (length = 16 bits)
console.log('0b'+acts.bit(16).padStart(32,'0'));   // 0b0111...1111
console.log('0b0'+acts.bit(31));             // 0b11111...11111  (length = 31 bits)
console.log('0b'+acts.bit(32).padStart(32,'0'));   // 0b1111...1111   ( = 32 bits)
console.log('\n ','----+'.repeat(6)+'--');
console.log(`Dad's birthday: ${acts.cdt(new Date(1925,1,1))}`);  // default US format
</script>

</body>
</html>

Les commentaires supplémentaires sont les bienvenus.


0 commentaires