var data = [
{
id:1,
account_name:'Akshay Patil',
debit:111,
credit:''
},
{
id:2,
account_name:'Bharat Chavan',
debit:222,
credit:''
},
{
id:3,
account_name:'Chetan Kore',
debit:333,
credit:''
},
{
id:4,
account_name:'Dilip Patil',
debit:444,
credit:''
},
{
id:5,
account_name:'Eshawr Dange',
debit:555,
credit:''
},
{
id:6,
account_name:'farhan Khan',
credit:666,
debit:''
},
{
id:7,
account_name:'Ganesh Shine',
credit:777,
debit:''
},
{
id:8,
account_name:'Hemant Birje',
credit:888,
debit:''
}
]
当生成随机数后从数组中删除对象时发生的问题是时间是随机数大于数组的长度然后错误就像无法读取属性。
这是我的main.s文件
function(){
user.wrapper.find('.randomMove').off('click').on('click', function(event){
var dice = {
sides: 6,
roll: function () {
var randomNumber = Math.floor(Math.random() * this.sides) + 1;
return randomNumber;
}
}
var result = dice.roll();
result--;
//setDataInTable(result);
user.data.splice(result,1);
});
}
使用此js我拼接生成的随机对象并设置为表数据
答案 0 :(得分:0)
这应该有效
var len = data.length;
var rand = Math.random() * (len - 0) + 0;
var selected = data[rand];
data.splice(rand, 1)
答案 1 :(得分:0)
您应该根据数组长度生成随机数。
var randomIndex = Math.floor( Math.random() * data.length );
// Index 0 - first
// Index (data.length-1) - last
现在删除随机元素:
var element = data.splice(randomIndex, 1)[0];
console.log(element);
之后,要获得另一个随机元素,您应该生成一个新的randomIndex并再次拼接。
答案 2 :(得分:0)
首先,您需要找到要删除的元素的索引:
var array = [1, 10, 100];
//edited to choose it random
var selectedItem = array[Math.floor(Math.random()*array.length)];
var index = selectedItem;
使用拼接后将其删除:
if (index > -1) {
array.splice(index, 1);
}
答案 3 :(得分:0)
我假设这是JavaScript,并且只有在从数组中删除元素后才会发生错误。我猜你正在浏览列表并试图改组内容。
这是怎么回事: 您从一个长度为8个元素的数组开始。然后你删除一个,使它长7个元素。然后,如果它选择要删除的元素8,则它不能,因为只剩下7个元素。这是您收到错误消息的方式。
请改用此代码:
var data = [
{
id:1,
account_name:'Akshay Patil',
debit:111,
credit:''
},
{
id:2,
account_name:'Bharat Chavan',
debit:222,
credit:''
},
{
id:3,
account_name:'Chetan Kore',
debit:333,
credit:''
},
{
id:4,
account_name:'Dilip Patil',
debit:444,
credit:''
},
{
id:5,
account_name:'Eshawr Dange',
debit:555,
credit:''
},
{
id:6,
account_name:'farhan Khan',
credit:666,
debit:''
},
{
id:7,
account_name:'Ganesh Shine',
credit:777,
debit:''
},
{
id:8,
account_name:'Hemant Birje',
credit:888,
debit:''
}
]
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function deleteRandom() {
data.splice(getRandomInt(0, data.length), 1);
}
console.log(data);
deleteRandom();
console.log(data);
此代码获取您的数组,找出它的长度,然后删除它知道的元素。出于演示的目的,这个将数组记录到控制台之前和之后。
答案 4 :(得分:0)
var data = [
{
id:1,
account_name:'Akshay Patil',
},
{
id:2,
account_name:'Bharat Chavan',
},
{
id:3,
account_name:'Chetan Kore',
},
{
id:4,
account_name:'Dilip Patil',
}
]
function removeItem(){
debugger;
var lengthOfArray = data.length;
var spilceId = Math.floor(Math.random() * lengthOfArray);
if(lengthOfArray > 0){
data.splice(spilceId,1)
}
// or remove data based on index of id
console.log(data);
}

<button onclick='removeItem()'>remove</button>
&#13;