Targeting Random Alive Actor in Battle

Hey there.

I have a common event that often triggers during battle and applies a state to a random alive actor in player's party.

I've been struggling to make it target a random alive party battle member, since there can be any amount of party members from 1 to 4 in the party, and any of them can be alive or dead.

Common event will let me assign an actor based on ID from a variable, but I don't know how to set this variable correctly.
Would appreciate some help, I feel I just lack knowledge of proper syntax to loop through alive party members and get ID of random one of them...
Try the other way around: get a random ID and then check if that actor has the death state or not. If yes, jump to beginning and reroll - if not give it the new state and finish.
Scriptwise:
Code:
var id = Math.randomInt($gameParty.aliveMembers().length);
$gameParty.aliveMembers()[id].addState(X);
Where X is the state ID that you wish to add.
Scriptwise:
Code:
var id = Math.randomInt($gameParty.aliveMembers().length);
$gameParty.aliveMembers()[id].addState(X);
Where X is the state ID that you wish to add.
You're a genius! Thanks!

Original thread: https://forums.rpgmakerweb.com/threads/targeting-random-alive-actor-in-battle.89406/