是否可以在JavaScript中洗牌对象中的元素?
我有一个目标:是否可以在JavaScript中洗牌对象中的元素?,javascript,object,shuffle,Javascript,Object,Shuffle,我有一个目标: { foo: 1, bar: 2, cheese: 3 } 我想洗牌的元素,所以它成为: { bar: 2, cheese: 3, foo: 1 } 或者其他的组合。是否有一个函数可以执行此操作?这是因为我想在对其使用JSON.stringify时产生不同的结果。我在互联网上能找到的唯一答案是指在数组中洗牌对象 谢谢。JS对象属性没有内在顺序。大多数JS运行时保留了添加键的顺序,但这不是语言要求,您不应该依赖它。例如,JSON.stringify总是按照字母顺序序列化键或随机
{ foo: 1, bar: 2, cheese: 3 }
我想洗牌的元素,所以它成为:
{ bar: 2, cheese: 3, foo: 1 }
或者其他的组合。是否有一个函数可以执行此操作?这是因为我想在对其使用JSON.stringify
时产生不同的结果。我在互联网上能找到的唯一答案是指在数组中洗牌对象
谢谢。JS对象属性没有内在顺序。大多数JS运行时保留了添加键的顺序,但这不是语言要求,您不应该依赖它。例如,
JSON.stringify
总是按照字母顺序序列化键或随机化键是完全有效的
如果顺序很重要,您可以保留一组两个数组来跟踪键和值。对象属性没有定义的顺序,并且没有定义或更改属性顺序的语言支持。根据语言规范,不必以任何方式保留顺序
如果您想要定义的顺序,您应该使用数组。您可以创建一个随机播放自定义函数吗
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
然后像洗牌一样使用它(myArray)
您需要将对象转换为数组…属性没有顺序,但此技巧对我有效(需要lodash):
要随机化对象中属性的顺序,您可以访问关键帧,将其洗牌,然后组合一个新对象。这里有一个函数:
让obj={“a”:1,“b”:2,“c”:3,“d”:4}
函数shuffleObject(obj){
//新obj回归
设newObj={};
//创建密钥数组
var keys=Object.keys(obj);
//随机密钥数组
sort(函数(a,b){return Math.random()-0.5;});
//保存在新数组中
键。forEach(函数(k){
newObj[k]=obj[k];
});
返回newObj;
}
console.log(shuffleObject(obj));
console.log(shuffleObject(obj));
console.log(shuffleObject(obj))代码>关于对象的问题,而不是数组他不能用对象做这件事,所以我提到了在数组中变换对象的想法。。。如果他那样做,它就会起作用。很好,兄弟。回答也很好-谢谢你的帮助。可悲的是,我只能接受一个,所以我不得不做出选择。。。
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function shuffleObject(obj) {
// Get object key into tmp array in random order
var keys = this.shuffle(_.keys(obj));
// instantiate new object who will be returned
var newObj = {};
// Iterate over keys to populate object with same properties in a different order
keys.forEach(function(elm, index){
newObj[elm] = obj[elm];
if(index === keys.length-1){
return newObj;
}
})
}
console.log(shuffleObject({ "A": 1, "B": 2, "C": 3, "D": 4 });
//{ "B": 2, "C": 3, "D": 4,"A": 1 }