Reputation: 370
So I've been learning JavaScript lately and decided to try out creating "scalable" serial code generator. However I'm very confused by arrays right nowthe way I'm trying to get it to work, I'm pretty sure there's a lot better way to do it but the problem now is that I'm trying to have each generated serial key to be put into array such as:
theCode = [{
"id":"1",
"code":"OOXCXAHEBUEIRVDASLWXBHTJN"
}];
So what I would need is: Each time I click a button, it will make a new index for the array and store the serial code in "code", and possibly set "id" for each new array index?
var alphSet = "abcdefghijklmnopqrstuvwxyz";
var numSet = "0123456789";
var alphNumSet = alphSet + numSet;
function randomised(len) {
return Math.floor(Math.random() * len);
}
function getRandom(str,set) {
return set[randomised(set.length)].toUpperCase();
}
function randomiseStrings(str) {
str = getRandom(str, alphSet);
return str;
}
function displayCode(length, rows) {
var currentRowNumber = 1;
// Stack up each randomised string to a array.
theCode = [{
"id":"1",
"code":"OOXCXAHEBUEIRVDASLWXBHTJN"
}];
function appendCode() {
if (typeof theCode === 'undefined') {
theCode[0] = [randomiseStrings()];
} else {
theCode[0] += [randomiseStrings()];
}
}
for(var i=0; i<length*rows;i++) {
appendCode();
}
}
displayCode(5, 5);
$("#button").click(function() {
console.log(theCode);
});
For any suggestion or idea I'd be grateful.
Upvotes: 0
Views: 55
Reputation: 700630
Start with an empty array ([]
) and use the push
method to add an object to the array:
function displayCode(length, rows) {
var currentRowNumber = 1;
var theCode = [];
for(var i = 0; i < length * rows; i++) {
theCode.push({
id: currentRowNumber++,
code: randomiseStrings()
});
}
return theCode;
}
$("#button").click(function() {
var theCode = displayCode(5, 5);
console.log(theCode);
});
Upvotes: 2