gpt4 book ai didi

javascript - 如何从node.js中的二维数组中获取随机项

转载 作者:行者123 更新时间:2023-12-03 05:28:03 25 4
gpt4 key购买 nike

我有一个二维的纬度和经度数组,如下 -

arrLoc = [
[18.3, 70.2],
[20.5, 75.4],
[19.3, 50.7],
[14.9, 40.5],

..... and so on, up to 10 items

我想从这个数组中选取一个随机的经纬度,以供进一步编码。

如何从这个二维数组中获取随机项?

最佳答案

要从 arrLoc 定义中获取随机值,只需使用 Math.random

var arrLoc = [
[18.3, 70.2],
[20.5, 75.4],
[19.3, 50.7],
[14.9, 40.5]
];

//random pair
var randIndex = Math.floor(Math.random() * arrLoc.length);
console.log("Latitude:"+arrLoc[randIndex][0]+", Longitude:"+arrLoc[randIndex][1]);

//two random values
var rand1 = Math.floor(Math.random() * arrLoc.length);
var rand2 = Math.floor(Math.random() * arrLoc.length);
console.log("Latitude:"+arrLoc[rand1][0]+", Longitude:"+arrLoc[rand2][1]);

无需接受它作为答案,Stack Overflow 已经对此给出了答案

关于javascript - 如何从node.js中的二维数组中获取随机项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41076246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com