简体   繁体   English

向数组添加多个值

[英]Add multiple values to an array

I have a map terrain like this: http://ast-ss.se/terrain/ 我有一个这样的地图地形: http : //ast-ss.se/terrain/

All the square's id's is in an array: 所有正方形的id都在一个数组中:

for(var i = 1; i <= 160; i++)
{
    squares.push(''+i);
}

When I click on a square, I want to take the index position of that square, and put in an another array, this works fine: 当我单击一个正方形时,我想获取那个正方形的索引位置,并放入另一个数组中,这样可以正常工作:

   angular.element('.click').click(function() {


                    var squareId = angular.element(this).attr('id');                //Rutans id
                    var squareIndex = squares.indexOf(squareId);                    //Rutans index som vi klickar på
                    var squareFirstIndex = squares.indexOf('1');                    //Utgå ifrån den första             

                    interval.push(squareIndex);  //Add the index here
                    console.log(interval);

However, this solution only adds one to array, one for each click. 但是,此解决方案仅向阵列添加一个,每次单击一次。 The thing I want is to add the whole interval of the square's indexe's. 我想要的是添加平方的索引的整个间隔。

Example: When you are on a square with the index 2, and click on an square with an index of 6, I want to stor the interval between 2 and 6(3,4,5) in the array when you doing one click. 示例:当您在索引为2的正方形上,然后单击索引为6的正方形时,我想在单击时在数组中存储2到6(3,4,5)之间的间隔。

How can I do this? 我怎样才能做到这一点?

You can get a range of an array with the slice method. 您可以使用slice方法获得数组的范围。 This doesn't change the original array and returns a copy. 这不会更改原始数组并返回一个副本。 The start index is includive, the end index is exclusive. 开始索引包括在内,结束索引是排他的。 If the start index is equal or greater than the end index, the resulting array is empty. 如果开始索引等于或大于结束索引,则结果数组为空。

So: 所以:

var here = squares.indexOf(here_id);
var there = squares.indexOf(there_id);
var interval;

if (here < there) {
    interval = squares.slice(here + 1, there);
} else {
    interval = squares.slice(there + 1, here);
}

console.log(interval);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM