This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 8 years ago.
How to do autocreate variables(names,ssns and more), depending how many arguments we have in function, for each element i wanna have column(but i dont wanna to create it in manual mode) each column put in automatically created div, other column into second div. (i need to create table depending from xml tags, depending how many elements and tags it has)
function GetTableResult(checkername, position //(can be much more//) {
var xmlResponse = xmlHttp.responseXML;
root = xmlResponse.documentElement;
names = root.getElementsByTagName(checkername); //need to autocreate
ssns = root.getElementsByTagName(position);
var stuff = "";
for(var i=0; i<names.length; i++) {
stuff += names.item(i).firstChild.data + "<br/>";
}
var position = "";
for(var j=0; j<ssns.length; j++) {
position += ssns.item(j).firstChild.data + "<br/>";
}
theD = document.getElementById("theD");
theD.innerHTML = stuff;
theB = document.getElementById("theB");
theB.innerHTML = position;
}
use the arguments variable:
function func() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
Related
This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 4 years ago.
I have made a piece of code that generates a random code of 12 characters. I am using Math.random and for-loops to do this. On the page you can write in an input how many codes you want.
What I want to do is save the generated codes in an array, however I can't do this because the for-loop and Math.random creates the code number by number and places them after each other. How can I add the whole 12 digit code to my array (so I can use it later)?
I've tried array.push with no luck. What works is outputting the numbers to DOM object in HTML, like this:
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
But that doesn't put the 12 digit code into a variable. I've also tried this:
var codeNumber = "";
codeNumber += mathRandom;
But that ends up in the variable value having only 1 digit.
<input type="number" id="numberOfCodes">
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
<script>
var numberOfCodes = document.querySelector("#numberOfCodes");
var arr = [];
function codeGen() {
x = numberOfCodes.value;
for (a = 0; a < x; a++) {
generate();
console.log("Generated code");
}
}
function generate() {
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
}
</script>
</div>
</body>
</html>
I expect the codes created (after some changes) to be added to the array, so that I can later use the codes on the page. Each individual 12-digit code needs to have its own place in the array.
This should work:
var result = [], stringResult;
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
result.push(mathRandom);
}
stringResult = result.join(''); // concatenates all the elements
console.log(stringResult);
The problem with your code is that + sign attempts to determine types of the operands and to choose the right operation, concatenation or addition. When adding stuff to innerHtml it treats the number as string. That is why it worked.
You'll want to refactor things so generating a single code is encapsulated in a single function (generate() here), then use that function's output, like this. (I hope the comments are enlightening enough.)
var numberOfCodes = document.querySelector("#numberOfCodes");
var resultDiv = document.querySelector("#result");
function codeGen() {
var nToGenerate = parseInt(numberOfCodes.value);
for (var a = 0; a < nToGenerate; a++) {
var code = generate(); // generate a code
// you could put the code in an array here!
// for the time being, let's just put it in a new <div>
var el = document.createElement("div");
el.innerHTML = code;
resultDiv.appendChild(el);
}
}
function generate() {
var code = ""; // define a local variable to hold the code
for (i = 0; i < 12; i++) { // loop 12 times...
code += Math.floor(Math.random() * 9); // append the digit...
}
return code; // and return the value of the local variable
}
<input type="number" id="numberOfCodes" value=8>
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
As this answer shows, this should work for you:
function makeRandCode() {
var code = "";
var ints = "1234567890";
for (var i = 0; i < 12; i++) {
code += ints.charAt(Math.floor(Math.random() * ints.length));
}
return code;
}
console.log(makeRandCode());
The problem is that you are adding numbers and what you really want is to concatenate them, the solution is to transform those numbers into String, then save them in the variable where you want to store them. An example:
2 + 2 = 4 and '2'+'2'='22'
Just use .toString() before save it in to the variable.
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 4 years ago.
I have a basic problem with for loop "tostring" iteration.
Description:
There are 12 <input type="text"> containers.
I want to detect when user writes si word in any 3 out of 12 containers.
If user types si exactly 3 times I set an alert called You made it!.
Problem:
Most likely that line is incorrect: if(cube[i].includes("si")).
Not sure how to check all containers in for loop just to count the number of si word. (adding number to string in for loop to call another variables e.g. cube1, cube2, cube3 etc.)
Any help would be appreciated, thank you :)
function transmute() {
var cube1 = document.getElementById("cube_slot1").value;
var cube2 = document.getElementById("cube_slot2").value;
var cube3 = document.getElementById("cube_slot3").value;
var cube4 = document.getElementById("cube_slot4").value;
var cube5 = document.getElementById("cube_slot5").value;
var cube6 = document.getElementById("cube_slot6").value;
var cube7 = document.getElementById("cube_slot7").value;
var cube8 = document.getElementById("cube_slot8").value;
var cube9 = document.getElementById("cube_slot9").value;
var cube10 = document.getElementById("cube_slot10").value;
var cube11 = document.getElementById("cube_slot11").value;
var cube12 = document.getElementById("cube_slot12").value;
var counter = 0;
for (var i = 1; i <= 12; i++) {
if (cube[i].includes("si")) {
counter += 1;
}
}
if (counter == 3) {
alert("You made it!");
}
}
Perhaps you could simplify your approach, but iterating over your elements within a for loop (via a dynamic id), and counting occasions where the si substring is found in input values.
If three or more cases are encountered, display the alert() and then break early from the loop:
function transmute() {
for(var i = 1; i <= 12; i++) {
var id = 'cube_slot' + i;
var value = document.getElementById(id).value;
if(value.includes('si')) {
counter += 1;
}
if(counter >= 3) {
alert("You made it!");
break
}
}
}
This question already has answers here:
Get HTML5 localStorage keys
(15 answers)
Closed 7 years ago.
I'm trying to print the names of all the keys stored in localStorage with each key in a separate line. This is my code:
function viewsaved(){
$('#saved').show();
var stuffsaved = Object.keys(localStorage);
var splitit = stuffsaved.split(',');
for (var i = 0 ; i < splitit.length ; i++ ){
$('#saved').append(splitit[i]+"<br>");
}
}
when I call the function, it does nothing.
How do you do this properly?
Object.keys returns an array, not a string. Just modify slightly:
var stuffsaved = Object.keys(localStorage);
for (var i = 0 ; i < stuffsaved.length ; i++ ) {
$('#saved').append(stuffsaved[i]+"<br>");
}
If you have or expect a lot of keys, I would suggest building the list in a temporary variable first to avoid frequent DOM update, for example:
var keys = Object.keys(localStorage);
var list = "";
for (var i = 0 ; i < keys.length ; i++ ) {
list += keys[i] + "<br>";
}
$('#saved').append(list);
This question already has answers here:
Javascript Object push() function
(10 answers)
Closed 8 years ago.
I have a object for which i am using push method and it gives me length one more than expected.
var Object=[];
var temp = {};
var j=0;
while(j<2){
temp.id= j+1;
//other properties setting
Object.push(temp);
j++;
}
console.log(Object.length);
gives me 3. Also I see three object values, first as empty second has id =1 and third has id =2.
.push is a function of Array and not Object and don't use variable names that cause ambiguity.
Use:
var arr = [];
var temp = {};
var j = 0;
while (j < 2) {
temp.id = j + 1;
//other properties setting
arr.push(temp);
j++;
}
console.log(arr.length);
(forgive me if I use slightly incorrect language - feel free to constructively correct as needed)
There are a couple posts about getting data from JSON data of siblings in the returned object, but I'm having trouble applying that information to my situation:
I have a bunch of objects that are getting returned as JSON from a REST call and for each object with a node of a certain key:value I need to extract the numeric value of a sibling node of a specific key. For example:
For the following list of objects, I need to add up the numbers in "file_size" for each object with matching "desc" and return that to matching input values on the page.
{"ResultSet":{
Result":[
{
"file_size":"722694",
"desc":"description1",
"format":"GIF"
},
{
"file_size":"19754932",
"desc":"description1",
"format":"JPEG"
},
{
"file_size":"778174",
"desc":"description2",
"format":"GIF"
},
{
"file_size":"244569996",
"desc":"description1",
"format":"PNG"
},
{
"file_size":"466918",
"desc":"description2",
"format":"TIFF"
}
]
}}
You can use the following function:
function findSum(description, array) {
var i = 0;
var sum = 0;
for(i = 0; i < array.length; i++) {
if(array[i]["desc"] == description && array[i].hasOwnProperty("file_size")) {
sum += parseInt(array[i]["file_size"], 10);
}
}
alert(sum);
}
And call it like this:
findSum("description1", ResultSet.Result);
To display an alert with the summation of all "description1" file sizes.
A working JSFiddle is here: http://jsfiddle.net/Q9n2U/.
In response to your updates and comments, here is some new code that creates some divs with the summations for all descriptions. I took out the hasOwnProperty code because you changed your data set, but note that if you have objects in the data array without the file_size property, you must use hasOwnProperty to check for it. You should be able to adjust this for your jQuery .each fairly easily.
var data = {};
var array = ResultSet.Result;
var i = 0;
var currentDesc, currentSize;
var sizeDiv;
var sumItem;
//Sum the sizes for each description
for(i = 0; i < array.length; i++) {
currentDesc = array[i]["desc"];
currentSize = parseInt(array[i]["file_size"], 10);
data[currentDesc] =
typeof data[currentDesc] === "undefined"
? currentSize
: data[currentDesc] + currentSize;
}
//Print the summations to divs on the page
for(sumItem in data) {
if(data.hasOwnProperty(sumItem)) {
sizeDiv = document.createElement("div");
sizeDiv.innerHTML = sumItem + ": " + data[sumItem].toString();
document.body.appendChild(sizeDiv);
}
}
A working JSFiddle is here: http://jsfiddle.net/DxCLu/.
That's an array embedded in an object, so
data.ResultSet.Result[2].file_size
would give you 778174
var sum = {}, result = ResultSet.Result
// Initialize Sum Storage
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] = 0;
}
// Sum the matching file size
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] += parseInt(result[i]["file_size"]
}
After executing above code, you will have a JSON named sum like this
sum = {
"description1": 20477629,
"description2": 1246092
};
An iterate like below should do the job,
var result = data.ResultSet.Result;
var stat = {};
for (var i = 0; i < result.length; i++) {
if (stat.hasOwnProperty(result[i].cat_desc)) {
if (result[i].hasOwnProperty('file_size')) {
stat[result[i].cat_desc] += parseInt(result[i].file_size, 10);
}
} else {
stat[result[i].cat_desc] = parseInt(result[i].file_size, 10);
}
}
DEMO: http://jsfiddle.net/HtrLu/1/