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

标签 javascript arrays node.js

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

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/

相关文章:

javascript - jQuery/Javascript - 多重正则表达式验证

javascript - 使用 Object.assign 更新对象后,在数组上调用 Push 方法会崩溃

javascript - 两个集合形成一个集合,用更新的字段替换重复项

java - 使用 JOptionPane 打印报告

javascript - Nodejs 中的 session 管理

javascript - socket.io 动态命名空间

Javascript - 将日期从 unixtime 格式化为 yyyy-mm-dd

javascript - 没有库的等效代码

c - 读取文件然后将数字存储在数组 C 中

node.js - 如何使用后端 Node js 在 Api.ai 中制作用于槽填充的 Webhook