admin管理员组文章数量:1407737
I have a variable with a dynamic value (from 1 to 15). Depending on the value of the variable, I want to create an array with the same length.
And, if for example the variable value is 1, I want to store A in the array, if the value is 6 I want to store A,B,C,D,E,F in the array and so on.
How do I achieve this? Thanks in advance.
I have a variable with a dynamic value (from 1 to 15). Depending on the value of the variable, I want to create an array with the same length.
And, if for example the variable value is 1, I want to store A in the array, if the value is 6 I want to store A,B,C,D,E,F in the array and so on.
How do I achieve this? Thanks in advance.
Share Improve this question edited Jul 30, 2010 at 11:35 Brock Adams 93.7k23 gold badges241 silver badges305 bronze badges asked Jul 30, 2010 at 7:51 peterpeter 672 silver badges6 bronze badges 7- 3 Is this homework? If so, please tag it as such. – Oded Commented Jul 30, 2010 at 7:55
- @Oded, Homework, in the middle of the summer? – Anders Commented Jul 30, 2010 at 7:55
- 2 @Anders - It is not summer in the south of our little globe, and not everyone in the world has summer vacation right now. Global munity and all, you know? – Oded Commented Jul 30, 2010 at 7:58
- Well, I am in Australia and it's winter here. No, it's not homework, thanks. – peter Commented Jul 30, 2010 at 7:58
- 2 wait, people outside the US have internet? woah! – Anurag Commented Jul 30, 2010 at 8:01
4 Answers
Reset to default 4var sizeOfArray = 6;
"ABCDEFGHIJKLMNO".slice(0, sizeOfArray).split('');
// ["A", "B", "C", "D", "E", "F"]
var arrSize = 4;
var myArray = new Array(arrSize);
or you can declare the array without size and then push a new element in it:
var myArray = new Array();
myArray.push(ITEM);
where ITEM is replaced by a variable or string or number you want to add in the array (will be added at the end of the array)
My 2 cents. (this function takes size > 26 into account)
<script type="text/javascript">
function buildAlphabetArray(size) {
var range = 26;
var arr = new Array();
for (var i = 0; i <= parseInt(size); i++) {
//calculate current index (recalc to number between 0 and range)
var j = (i < (range-1) ? i : (i - range * parseInt(i / range)));
//get the char value of ascii 65 + index (charAt(65)==A)
arr[i] = String.fromCharCode(j + 65); //
}
//test
//alert(arr.join(""));
return arr;
}
</script>
var a = 5;
var arr = new Array(a);
for (var i = 0;i<a;i++) {
arr[i] = String.fromCharCode(65+i);
document.write("arr["+i+"] = '"+arr[i]+"'<br/>");
}
本文标签: Create array based on variable value with javascriptStack Overflow
版权声明:本文标题:Create array based on variable value with javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744670544a2618795.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论