function randAry(i_ary){
var aryKeys = Object.keys(i_ary);
var index = aryKeys[Math.floor(Math.random() * aryKeys.length)];
return i_ary[index];
}
function randAry2(i_ary){
var aryKeys = Object.keys(i_ary);
var index = aryKeys[Math.floor(Math.random() * aryKeys.length)];
retVal = i_ary[index];
if(i_ary instanceof Array){
i_ary.splice(index,1);
}else{
delete i_ary[index];
}
return retVal;
}
var ary = [0, 2, 4, 6, 8, 10];
console.log("ary 初期状態:" + ary);
console.log(randAry(ary))
console.log("ary randAry後:" + ary);
console.log(randAry2(ary));
console.log("ary randAry2後:" + ary);
var hogeArr = { test1 : "田中" , test2 : "佐藤" , test3 : "山本" , test4 : "鈴木" } ;
console.log(hogeArr)
console.log(randAry(hogeArr))
console.log(hogeArr)
console.log(randAry2(hogeArr))
console.log(hogeArr)
参考
JavaScriptの配列の要素を削除する(delete演算子とspliceメソッド) – 山本隆の開発日誌
JavaScript で配列を判定する正しいやり方 - Qiita