I am trying to pass this arr into a function, one element at a time. I have more work to do beyond that, but I cannot even get it to send the element to the square function, so this is just a hurdle that I don't understand? Anyway, this is the code:
var arr = [1,2,3,4];
function square(element){
return element * element;
}
function applyFunction(arr, square){
for(var i = 0; i <= arr.length-1; ++i){
alert(square(arr[i]));
}
}
applyFunction(arr,square());
Any help would be appreciated, as I am sure this is simple for you guys.
Modify your last line from
applyFunction(arr,square());
to
applyFunction(arr,square);
Related
i wanna generate a 3x3 field. I want to do this with JS, it shall be a web application.
All fields shall inital with false. But it seems so that my code is not working correctly, but i don't find my fault. The goal is, that every spacesector is accessible.
Thats my idea:
// define size
var esize = generateSpace(3);
}
space[i] = false is replacing the array with a single boolean value false, not filling in all the entries in array you just created. You need another loop to initialize all the elements of the array.
function generateSpace(x) {
var space = [];
for (var i = 0; i < x; i++) {
space[i] = [];
for (var j = 0; j < x; j++) {
space[i][j] = false;
}
}
return space;
}
Also, your for() loop condition was wrong, as you weren't initializing the last element of space. It should have been i < space.length.
And when it's done, it needs to return the array that it created.
Since I got somewhat bored and felt like messing around, you can also initialize your dataset as shown below:
function generateSpace(x) {
return Array.apply(null, Array(x)).map(function() {
return Array.apply(null, Array(x)).map(function() {
return false;
});
});
}
The other functions work equally well, but here's a fairly simply looking one using ES6 that works for any square grid:
function generateSpace(x) {
return Array(x).fill(Array(x).fill(false));
}
I have a 2d observable array called textFields:
var t1 = ko.observableArray([{val: 0}, {val:0}])
self.textFields = ko.observableArray([t1]);
And I have a function called solve that is supposed to take an argument:
self.solve = function(arr){
console.log(arr);
}
In my html, I have associated that function with a link click that passes textFields as an argument to solve:
<a id='solveBtn' href='#' data-bind='click: solve(textFields)'>Solve</a>
I thought I'd now get my textFields-array printed out. But instead, I get []. When I look at the variable in the debugger in Chrome, I also just see []. Why is that? Why is textFields not properly passed to solve?
EDIT:
I made the js now look like this:
self.solve = function(arr){
console.log(arr());
}
But know I want to pass this observable array to another function (which is supposed to make a 'normal' array out of it:
var normalize = function(arr){
var retArr = [];
console.log(arr().length);
for(var i = 0; i < arr.length; i++){
var temp = [];
for(var j = 0; j < arr()[i]().length; j++){
temp.push(arr()[i]()[j].val);
}
console.log(temp);
retArr.push(temp);
}
return retArr;
}
The console.log(arr()) gives me the following error: Message: object is not a function. When I treat arr as a normal array, the for-loop is never executed. I gues that's because arr[i] has length 0.
Thank you very much for your answers!
Tony
Try doing this in markup to get array values in your solve method
<a id='solveBtn' data-bind='click: function(){solve(textFields())}'>Solve</a>
or modify your script as follows
self.solve = function(arr){
console.log(arr());
}
Quick note : In your sample markup, you are setting a function with parameter to the click event. This will cause the function to get executed during page load. It is always safe to wrap it in a function block as below.
<a id='solveBtn' data-bind='click: function(){solve(textFields)}'>Solve</a>
I'm putting together this script which pulls two child elements from a containing div #mini_ads, adds them to an array. I want to be able to use the array to select them via index in order to manip. them individually.
I know I can just select them w/o even using an array of course, but I want this array as I may add multiple more elements later.
The issue is that I am not able to select the items individually by their index in the array. The current script I've got going is selecting and manipulating both objects in the array as if they're both index[0].
var miniAds = $('#mini_ads');
var elements = miniAds.children();
var changeWtime;
var adsArr = new Array();
var i = 0;
var x = 0;
adsArr.push(elements);
console.log(adsArr);
adsArr[i].css("display", "none");
var changeWtime = setInterval(function () {
for (x; x < 1; x++) {
return x;
while (x > i) {
adsArr[1].css("display", "block");
}
};
}, 5000);
console.log(x);
changeWtime;
I am not sure where I'm going wrong here. Assistance will be much appreciated. Thanks in advance.
Issues with your code
You're creating a double array when you push elements into 'adsArr':
adsArr.push(elements);
You're throwing a return statement in the for loop:
for (x; x < 1; x++ ){
return x;
// ...
You have a double loop for no reason while inside of the for.
Solution
I was going to explain the solution to this verbally, but after coding an example I realized that there is too much to explain this is another solution similar to yours:
var miniAds = $('#mini_ads'),
elements = miniAds.children(),
i = 2,
x = 0;
elements.hide();
var changeWtime = setInterval(function () {
if ( x < i ) {
$(elements[x]).show();
}
x++;
}, 5000);
Link to example on jsbin.
Hi u should push child divs as below function does and after that i believe u can perform ur task...
var adsArr= [];
$('#mini_ads').children().each(
function(i){
adsArr.push(this);
});
In plain Javascript use .styles()
.css() which is a JQuery method but not Javascript
ref http://www.w3schools.com/js/js_htmldom_css.asp
I'm trying hard to learn javascrip+jquery on my own, and also trying to learn it right. Thus trying to enforce the DRY rule.
I find myself stuck with a problem where I have an array,
var animals = [4];
a function,
var legs = function(amount){
this.amount = amount;
this.body = Math.floor(Math.random()*amount)+1;
}
and an evil for loop. I also have 5 div's called printAnimal1, printAnimal2 and so on.. In which I wish to print out each value in the array into.
for(i = 0; i < animals.length; i++){
animals[i] = new legs(6);
$(".printAnimal"+i).append("animals[i]");
}
I feel as if I'm close to the right thing, but I cant seem to figure it out. I also tried something like this:
for(i = 0; i < animals.length; i++){
animals[i] = new legs(6);
$this = $(".printAnimal");
$(this+i).append("animals[i]");
}
But one of the problems seem to be the "+i" and I cant make heads or tails out of it.
I also know that I can simply do:
$(".printAnimal1").append("animals[i]");
$(".printAnimal2").append("animals[i]");
$(".printAnimal3").append("animals[i]");
...
But that would break the DRY rule. Is it all wrong trying to do this with a for loop, or can it be done? Or is there simply a better way to do it! Could anyone clarify?
Your first attempt should be fine, as long as you take "animals[i]" out of quotes in your append() call ($(".printAnimal"+i).append(animals[i]))
Also, I assume you declared var i; outside your for loop? If not, you'll want to declare it in your for loop (for(var i=0....)
EDIT: problems with your fiddle
you never call startGame()
you didn't include jQuery
you can't (as far as I know) append anything that isn't html-- in your case, you're trying to append a js object. What do you want the end result to look like?
http://jsfiddle.net/SjHgh/1/ is a working fiddle showing that append() works as you think it should.
edit: forgot to update the fiddle. Correct link now.
EDIT: reread your response to the other answer about what you want. http://jsfiddle.net/SjHgh/3/ is a working fiddle with what you want. More notes:
You didn't declare new when you called DICE
you have to reference the field you want, (hence dices[i].roll), not just the object
Just a few comments:
This is declaring an array with only one item and that item is the number 4
var animals = [4];
In case you still need that array, you should be doing something like:
var animals = []; // A shiny new and empty array
and then add items to it inside a for loop like this:
animals.push(new legs(6)); //This will add a new legs object to the end of the array
Also, what is the content that you are expecting to appear after adding it to the div?
If you want the number of legs, you should append that to the element (and not the legs object directly).
for(i = 0; i < animals.length; i++){
animals.push(new legs(6));
$(".printAnimal"+i).append(animals[i].body);
}
Adding another answer as per your comment
var i, dicesThrown = [];
function throwDice(){
return Math.ceil(Math.random() * 6);
}
//Throw 5 dices
for (i=0 ; i<5 ; i++){
dicesThrown.push( throwDice() );
}
//Show the results
for (i=0 ; i<5 ; i++){
$("body").append("<div>Dice " + (i+1) + ": " + dicesThrown[i] +"</div>");
}
Please explain this to me. I'm trying to create an array of arrays with a for loop. When it didn't work, I tried simplifying the code to understand what Javascript is doing, but the simple code doesn't make sense either.
function test(){
var sub_array = [];
var super_array =[];
for (var i=1;i<=3;i++){
sub_array.push(i);
super_array.push(sub_array);
}
alert(super_array);
}
I expect to see [1; 1,2; 1,2,3].
Instead I get [1,2,3; 1,2,3; 1,2,3].
I get the same phenomenon if I loop 0-2 and assign by index.
You're always pushing a reference to the same array into your super-array.
To solve that problem, you can use slice() to clone the sub-array before pushing it:
function test() {
var sub_array = [];
var super_array = [];
for (var i = 1; i <= 3; i++) {
sub_array.push(i);
super_array.push(sub_array.slice(0));
}
alert(super_array);
}
EDIT: As Dan D. rightfully points out below, you can also call concat() without arguments instead of slice(0). It's faster according to this article (I did not measure it myself):
for (var i = 1; i <= 3; i++) {
sub_array.push(i);
super_array.push(sub_array.concat());
}
When you push "sub_array", you're not pushing a copy of it. You end up with the same array three times in "super_array". (I should say that you're pushing a reference to the same array three times.)
You could do this:
// ...
super_array.push(sub_array.slice(0));
to make a copy.
well. You have to understand, that Array, Objects, Functions, etc. are references in javascript (only Numbers(Int,Floats,etc) and Strings are passed "by-value", which means, that the value is copied/duplicated)!
if you have an var a=[];, und say var b=a and add b.push("bla"), then alerting a, will show you the "bla" entry, even though you added it to b.
In other words; a and b is to javascript like a note on the frige from mom saying "the sandwhich on the left is for you." And then you know, that to take the left one and not just any random sandwich from the fridge. She also could have written another note (variable b) on your house' door, so that you knew where to go and look for the sandwich if you are in a hurry.
If she would have stuck a sandwich to the door.. well, that would be ackward. And JS thinks the same about it :)
so the solution to your problem is as fallows;
function test(){
var super_array =[];
for (var i=1;i<=3;i++){
var subarray=[];
for (var u=1;u<=4-i;u++){
sub_array.push(u);
super_array.push(subarray);
}
}
alert(super_array);
}
by redefining the subarray, you create a new reference. So that the variable b (the second note on the hous' door) now points in the direction of a different sandwich - maybe dad's sandwich.
I hope I could help you understand this.
Note that you are pushing the same array into super_array for each iteration in the for-loop. Try instead the following:
function test(){
var sub_array = [];
var super_array =[];
for (var i=1;i<=3;i++){
sub_array = sub_array.slice(0,sub_array.length);
sub_array.push(i);
super_array.push(sub_array);
}
alert(super_array);
}
It is same sub_array that you are adding to the super_array. So why it has to be different.
You are not creating a new array and pushing into a super_array.
sub_array is stored as a reference in super_array this means that when you change sub_array the change is reflected inside super_array