在javascript中存储数组中的坐标 [英] storing coordinates in array in javascript

查看:156
本文介绍了在javascript中存储数组中的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将坐标存储到javascript中的数组中,
我是JavaScript的新手,并不知道如何去做。

I want to store coordinates into an array in javascript, I am new to javascript and do not have an idea how to do it.

任何帮助将不胜感激。

推荐答案

function storeCoordinate(x, y, array) {
    array.push(x);
    array.push(y);
}

var coords = [];
storeCoordinate(3, 5, coords);
storeCoordinate(19, 1000, coords);
storeCoordinate(-300, 4578, coords);

coords[0] == 3   // x value (even indexes)
coords[1] == 5   // y value (odd indexes)

// to loop through coordinate values
for (var i = 0; i < coords.length; i+=2) {
    var x = coords[i];
    var y = coords[i+1];
} 



选项2(数组中的简单对象):


$ b $

Option 2 (simple object in an array):

function storeCoordinate(xVal, yVal, array) {
    array.push({x: xVal, y: yVal});
}

var coords = [];
storeCoordinate(3, 5, coords);
storeCoordinate(19, 1000, coords);
storeCoordinate(-300, 4578, coords);

coords[0].x == 3   // x value
coords[0].y == 5   // y value

// to loop through coordinate values
for (var i = 0; i < coords.length; i++) {
    var x = coords[i].x;
    var y = coords[i].y;
} 

这篇关于在javascript中存储数组中的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆