在Javascript中获取数组的索引并存储在变量中

时间:2016-01-15 04:31:42

标签: javascript arrays

我有一个函数getStoreAreaData()。它会遍历我的数组列表

//list of array
storeAreaData = [1,2,3,4,5,6,7,8];


function getStoreAreaData(){
    //storeareadata mag hohold ng array ng storeAreaData
    holdStoreAreaData = storeAreaData;

    //now holdlengtharray holds the array of holdstoreareadata
    var holdLengthArray = holdStoreAreaData.length;

    for (var i = 0; i < holdLengthArray; i++) {
            //this holdgetStoreAreaData now holds all of the data of the array;
            holdGetStoreAreaData = holdStoreAreaData[i];
            document.write(holdGetStoreaAreaData);
            //create a variable that will hold the array

    }
}

for循环内部,我将holdStoreAreaData存储在holdGetStoreAreaData内。我的问题是我想把它放在一个保存索引的变量中,还是有其他方法直接通过holdGetStoreAreaData访问索引?

E.g。

之类的东西
holdGetStoreAreaData[0] = 1;
holdGetStoreAreaData[1] = 2;
holdGetStoreAreaData[2] = 3;
holdGetStoreAreaData[3] = 4;

2 个答案:

答案 0 :(得分:0)

您需要附加到列表中:

holdGetStoreAreaData = []
for (var i = 0; i < holdLengthArray; i++) {
        holdGetStoreAreaData.push(holdStoreAreaData[i]);
}

克隆数组的更好方法是

holdGetStoreAreaData = holdStoreAreaData.slice(0);

请参阅slice文档。

答案 1 :(得分:0)

here is the image of tabular array

<!DOCTYPE html>
<html>
<body>
<div>
<input type="button" onClick="getStoreAreaData()" value="Click">
</div>
<script type="text/javascript">
var storeAreaData = [1,2,3,4,5,6,7,8];

function getStoreAreaData(){

var holdGetStoreAreaData=[];

for (var i = 0; i < storeAreaData.length; i++) 
{
holdGetStoreAreaData[i]=storeAreaData[i];
console.log("holdGetStoreAreaData["+i+"]:",holdGetStoreAreaData[i]);
}
}
</script>
</body>
</html>