Accessing An Array from within a function using JavaScript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I searched the forum but didn't see a similar question or answer for the question I am about to ask, however if it is duplicated please provide a link and I will view the answer in that post.
Is it possible to access objects in a array from within a closure/ function? I am attempting to do so for the purpose of experimentation.
Here is the code I put together in firebug. I am receive 'undefined'.
var checkers = [1, "string", null];
var i, txt = "";
function myFunction(checkers){
for(var i = 0; i < checkers.length; i++ ){
txt += checkers[i] + " ";
console.log(txt)
}
}
myFunction(checkers);

Absolutely possible, one of JavaScript's strenghts.
Your issue is that you aren't calling your function. Also you don't need a parameter to myFunction since it closes over the context and knows about checkers.
Just delete the paramter and after your code add myFunction() to call it.
var checkers = [1, "string", null];
var i, txt = "";
function myFunction(){
for(var i = 0; i < checkers.length; i++ ){
txt += checkers[i] + " ";
console.log(txt)
}
}
myFunction();
The reason you are getting undefined is because theres not value returned to the console when declaring a function, just like you'd get undefined if you ran:
var t = 'asd'

var checkers = [1, "string", null];
var i, txt = "";
function myFunction(checkers){
for(var i = 0; i < checkers.length; i++ ){
txt += checkers[i] + " ";
console.log(txt)
}
}
myFunction(checkers);

I just ran it and I get:
1
1 string
1 string null
undefined
Since the function doesn't return anything, Firebug displays undefined at the end.

Related

I am Unable to get output in this JS before loop termination [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
i want to get my output after every iteration of loop but it gives me output when loop is terminated.i am unable to get why am facing this issue as am newbie to JS. after i press N to terminate loop n prompt get closed i get output on webscreen.maybe i look stupid but i am not able to solve it own my own n PS vote Postive for my question as i am geting question ban.
<script type="text/javascript">
do{
var value1=prompt("enter 1st number::"," ");
var value2=prompt("enter 2nd number::"," ");
var op=prompt("Enter operator from(+,-,*,/,%age,average):");
if (op=="+")
{
var result=parseInt(value1)+parseInt(value2);
document.write("addition result is ="+result );
document.write("<br/>");
}
else if(op=="-")
{
var result=parseInt(value1)-parseInt(value2);
document.write("substraction result is ="+result );
document.write("<br/>");
}
else if (op=="*")
{
var result=parseInt(value1)*parseInt(value2);
document.write("multiplication result is ="+result);
document.write("<br/>");
}
else if (op=="/")
{
var result=parseInt(value1)/parseInt(value2);
document.write("division result is ="+result );
document.write("<br/>");
}
else if (op=="%age")
{
var result=(parseInt(value1)/parseInt(value2))*100;
document.write("percentage of value1 with value 2 is ="+result );
document.write("<br/>");
}
else if (op=="average")
{
var result=(parseInt(value1)+parseInt(value2))/2;
document.write("average is ="+result );
document.write("<br/>");
}
else
{
displa("Invalid input :" );
document.write("<br/>");
}
var choice=prompt("Do you want to continue (Y/N)::"," ");
}
while(choice=="Y"||choice=="y");
</script>
There is a syntax error in your code ParseInt should be parseInt, additionnaly, it is recommended to use the static method of the Number object: Number.parseInt as it is generally safer.

Javascript - Passing from a DOM element to array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Hello and thank you for your time.
Here is the code :
<script>
var names = document.getElementsByClassName('xx');
var ar = [];
for (var i = 0, c = names.length ; i < c ; i++) {
ar[i] = names[i].innerHTML;
alert(ar[i]);// the results are : undefined
}
</script>`
I've tried to use the method tostring, or to push the results into the array but without success.
Thanks
Your main issue seems to be fixed. Make sure the DOM has been loaded before you try to run your code, and there is no need for two variables in your loop. Simplify it like below:
window.onload = function () {
var names = document.getElementsByClassName('xx');
var ar = [];
for (var i = 0 ; i < names.length ; i++) {
ar[i] = names[i].innerHTML;
alert(ar[i]);
}
};
Fiddle
ar.length equals 0, because you just declare the array, but dont put anything into it. I think what you wanted to do is the following:
var names = document.getElementsByClassName('xx');
var ar = [];
for (var i = 0 ; i < names.length ; i++) {
ar[i] = names[i].innerHTML;
alert(ar[i]);
}

Iterating through an array returns null when using getElementbyID [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to loop through a array of six numbers and modify a corresponding form element like so..
for(var x in numbers) { document.getElementById('r' + numbers[x]).value++; }
However this doesn't update the text field and the debugger says Type Error: document.GetElementById(...) is null. However the following code works as expected
var t = 25;
document.getElementById('r' + t).value++;
Can anyone shed any light on this? I'm not really a javascript programmer and am cobbling something together from code examples and I just can't see why the second case works but not the first.
ps. And yes I've tried with the more correct for (var i=0; i < numbers.length; i++) {} format ;)
If this setup in jsbin is similar to what you have and it doesnt work...I'd suspect that your code is not finding the element in the DOM and you need to run the code when the DOM has actually loaded.
http://jsbin.com/fasibuse/1/edit?html,js,output
I think a more generic solution that would do the same thing ( increase the elements by 1 )...would be
var formElements = document.forms[0].getElementsByTagName( 'input' );
for (var el of formElements) {
el.value++;
}
Read code directly:
var numbers = [10,20,30,40];
for(var x in numbers) {
console.log(x); // <-- output 0,1,2,3 (the indexes, not the content)
}
You should use
numbers.forEach(function (x) {
document.getElementById('r' + numbers[x]).value++;
});
Something like this should work:
<!DOCTYPE html>
<html>
<body>
<input id="sparky1" value="1"><br>
<input id="sparky2" value="3"><br>
<input id="sparky3" value="5"><br>
<input id="sparky4" value="7"><br>
<input id="sparky5" value="9"><br>
<script>
for (var i=1; i < 6; i++) {
document.getElementById('sparky' + i).value = parseInt(document.getElementById('sparky' + i).value) + 1;
}
</script>
</body>
There is invalid access of array element, here is correct one. try this one.
for(var x in numbers) { document.getElementById('r' + x).value++; }
this will work fine.

Parse.com Overwrites my results when Javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm not sure what am I doing wrong.
When running the attached code I would expect to see 100 rows inside Parse.com.
Instead, I only see only one.
For some reason, Parse.com is overwriting the same line 100 times.
And ideas? :/
Me.
function simplewrite() {
Parse.initialize("********************, ***********************");
var Numbers = Parse.Object.extend("Numbers");
var numbers = new Numbers();
for (var i=0; i<100; i++) {
numbers.set("number", i);
numbers.save(null, {
success: function(numbers) {
console.log("YES " + i);
},
error: function(numbers, error) {
console.log("no! " + i);
console.log(error);
}
}); // End
};
};
Your for loop is updating the same numbers variable over and over. Try moving the initialization of numbers to inside your for loop:
// ...
for (var i=0; i<100; i++) {
var numbers = new Numbers();
// ...

Javascript syntax error? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I keep getting a syntax error that I am missing ";" before statement var numDashes += '-';
I am just trying to pass a number to a dashes method and add the respective number of dashes using recursion. Sorry i'm a Java person. Please help.
function dashes(number) {
for (var i=0; i<number; i++){
var numDashes += '-';
}
return numDashes;
}
console.log(dashes(3))
You should declare numDashes first with an empty string.
function dashes(number) {
var numDashes = '';
for (var i=0; i<number; i++){
numDashes += '-';
}
return numDashes;
}
function dashes(number) {
var numDashes = "";
for (var i=0; i<number; i++){
numDashes += '-';
}
return numDashes;
}
console.log(dashes(3))
This should work :) When creating a variable always initialized with something. Otherwise it will be as 'undefined'
Above answer are correct. you can't apply any operation when you define variable. First need to be define variable after that you can implement any operation. So, define "numDashes" variable before loop and than apply "+=" operator in loop.
Correct Syntax:
function dashes(number) {
var numDashes = "";
for (var i=0; i<number; i++){
numDashes += '-';
}
return numDashes;
}
console.log(dashes(3))

Categories

Resources