How to randomize traits?

So I found out the code for giving traits to an item, which is:
item.traits.push({"code":21, "dataId":2, "value":1.10}) --> this will give +10% ATK trait to the item

However, I'm struggling to make it so the value given is random from +5% to +10% and the dataID to random 0 to 7.
So the question is... how can I randomize these?

I tried using variables but it doesn't work 🙁

here's the code I tried that didn't work:
Code:
var statparams = ['0', '1', '2', '3', '4', '5', '6', '7'];
var randomStat = statparams[Math.floor(Math.random()*statparams.length)];
// then declare that randomStat is the dataId
Try this method

Random param.png
So I found out the code for giving traits to an item, which is:
item.traits.push({"code":21, "dataId":2, "value":1.10}) --> this will give +10% ATK trait to the item

However, I'm struggling to make it so the value given is random from +5% to +10% and the dataID to random 0 to 7.
So the question is... how can I randomize these?

I tried using variables but it doesn't work 🙁

here's the code I tried that didn't work:
Code:
var statparams = ['0', '1', '2', '3', '4', '5', '6', '7'];
var randomStat = statparams[Math.floor(Math.random()*statparams.length)];
// then declare that randomStat is the dataId
You certainly can define property values as variables! I imagine you've made a mistake somewhere...I notice you've omitted the part where you assign the trait to the item, for instance? In the code you quoted, statparams should probably be an array of numbers, not strings, e.g.
Code:
var statParams = [0,1,2,3,4,5,6,7];
var randomStat = statParams[Math.randomInt(statParams.length)];
Or, more simply:
Code:
var randomStat = Math.randomInt(8);
(Math.randomInt is a shortcut method defined in RMMV's base code, very handy~ 😂)

However, note that by default items are not instanced: every item gets its stats from the database ($dataItems/$dataArmors/$dataWeapons), and those stats are loaded once, when the game boots. The item-related values present in save files are ID and class (Item, Weapon, or Armor), which is sufficient to determine the corresponding database record. With that in mind, I would not recommend changing the database values in the way you suggest. I mention this because it's unclear what "item" you might be modifying. 😅

If you want to give each item stats independently of the other items of the same type, you may be interested in the "Independent Item" settings of Yanfly's Item Core plugin. It comes with notetags including <Random Variance: x> and <On Creation Eval> (with the latter you can probably use the code you've quoted to add traits to items at runtime).

Original thread: https://forums.rpgmakerweb.com/threads/how-to-randomize-traits.114586/