[使用最新的Google chrome,我正在运行以下代码:
(data) => { //data is a list of json tuples that look like [{x: __, y: ___}, ...]
var rand = () => Math.random() * data.length;
const placeholder = [...Array(10).keys()].map(_ => {
const idx = Math.floor(rand());
return data[idx];
});
};
我希望此功能要做的是对输入数据的10个子集进行采样,并以相同格式返回它。在map函数的每次迭代中,我都在打印对象,它看起来像预期的一样(请参见图片)。奇怪的是,然后我在“占位符”数组中看到的结果是,每个Release_Date键的值都与placeholder [0] ['Release_Date']的值相同,而它们各自都是唯一的值。 Production_Budget看起来不错。我不知道这是怎么回事,我很困惑。有谁知道发生了什么吗?
您的函数从不返回任何东西。
const getSample = (data) => { //data is a list of json tuples that look like [{x: __, y: ___}, ...]
const rand = () => Math.random() * data.length;
const placeholder = [...Array(10).keys()].map(_ => {
const idx = Math.floor(rand());
return data[idx];
});
/* | | | | | | | */
/* V V V V V V V */
return placeholder;
};
const data = Array(30).fill(0).map(() => ({
x: Math.random.between(0, 600),
y: Math.random.between(0, 600),
}));
const sample = getSample(data);
console.log(sample);
<script src="https://cdn.jsdelivr.net/gh/olian04/better-random/src/index.js"></script>
如果需要的话,您也可以简化代码。例如:
const getSample = (data, sampleSize=10) => Array(sampleSize).fill(0)
.map(() => Math.random.select(data));
const data = Array(30).fill(0).map(() => ({
x: Math.random.between(0, 600),
y: Math.random.between(0, 600),
}));
const sample = getSample(data);
console.log(sample);
<script src="https://cdn.jsdelivr.net/gh/olian04/better-random/src/index.js"></script>