I've been trying to figure this out by re-writing my forLoop multiple times, look online for example and even checked out MDN and gotten to the point I need someones help.
Now the test error I get is:
1) loops forLoop(array) adds `"I am ${i} strange loop${i === 0 ? '' : 's'}."` to an array 2
5 times:
ReferenceError: forLoop is not defined
My current code looks like this:
function forLoop(array){
var newArr = [];
for (var i = 0; i < array.length; i++){
if (i === 1) {
newArr.push("I am 1 strange loop.")
} else {
newArr.push(`I am ${i} strange loop${i === 0 ? '' : 's'}.`)
}
}
return newArr
}
Thinking process:
I need a loop to iterate the array being place.
I need a new array to input something each time we loop around.
Call a for loop. Set i to 0 as we will start from there.
Find the end point which is less than array.length
Place increment since we will be going up from 0 each time we loop.
Make if and else statement
Add if statement is true to the new array
Return the new array in the end
Is there something I'm not understanding or missing? Really can't seem to crack this.
For additional information about the test. The test for this problem is:
describe('forLoop(array)', () => {
it('adds `"I am ${i} strange loop${i === 0 ? \'\' : \'s\'}."` to an array 25 times', () => {
const [array, t] = makeArray()
const strangeArray = forLoop(array)
expect(strangeArray.length).to.equal(t + 25)
const testArray = strangeArray.slice(array.length)
for (let i = 0, l = testArray.length; i < l; i++) {
let s = i === 1 ? "I am 1 strange loop." : `I am ${i} strange loops.`
expect(testArray[i]).to.equal(s)
}
})
})
ReferenceError: forLoop is not defined means that the Javascript interpreter can't find the function "forLoop".
Possible causes:
The test and the function are not in the same file and you made a mistake while including the file which contains the function. Make sure you include your file with the function before the test file.
The test doesn't have access to the function because it's in a different scope of your application.
I tested the forLoop function myself and it worked for me. I don't think the problem is in the forLoop function.
Related
I am not a coder, I am messing around with some JavaScript as part of modding a game, so bear with me. This game supports es5/everything Chromium 28 supported.
I had code which pushed a string to an array from a variable, and when the variable was undefined a fixed string was pushed instead:
slotsArray.push({
landing_policy: ai.landing_policy || 'no_restriction'
});
The setup changed such that where ai.landing_policy was set it would contain multiple values, so it become an array. When it wasn't set only a single entry was required.
The same code does not appear to work where an array is in place:
for (var i = 0; i < count; i++) {
slotsArray.push({
landing_policy: ai.landing_policy[i] || 'no_restriction'
});
}
An error is produced because it's trying to check a value from a variable that hasn't been defined. I expected that to cause it to use the fixed value, but apparently that's not what happens, it just fails.
I've changed my approach to the code seen below in full:
if (Array.isArray(ai.landing_policy)) {
for (var i = 0; i < count; i++) {
slotsArray.push({
landing_policy: ai.landing_policy[i]
});
}
}
else {
slotsArray.push({
landing_policy: ai.landing_policy || 'no_restriction'
});
}
This code works, but what I'm looking to understand is whether this was the best solution? The old method felt elegant, while the new one looks a little clumsy.
You can use the ternary operator(? :).
It will return the second value if the first is true, and the third otherwise.
I've used array instanceof Array instead of Array.isArray(array) to support ES5.
var isArray = ai.landing_policy instanceof Array
for (var i = 0; i < (isArray ? count : 1); i++) {
slotsArray.push({
landing_policy: isArray ? ai.landing_policy[i] : ai.landing_policy || 'no_restriction'
});
}
Elegant solution not always converse to the most readable/desirable. I would probably do something like:
const formattedPolicy = ai.landing_policy.map(policy => policy || 'no_restriction');
slotsArray = [...formattedPolicy ];
Course this has to imply that the ai.landing_policy is always an array. If you need to double check first you could also do:
const formattedPollicy = ai.landing_policy.constructor === Array
? ai.landing_policy.map(policy => policy || 'no_restriction');
: [ai.landing_policy]
Looks like an elegant or short imho but your code is way more readable.
for(var i=0; i < imageFiles.length; i++)
{
console.log('index value : ' + i)
let item = imageFiles[i]
let file = item.getAsFile()
let oValue = await self.getOrientation(file)
console.log('orientation value : ' + oValue)
}
The for loop above is only executing once, could someone provide a solution that will make the loop iterate over all the files in the array ?
From within the parentheses, you defined the variable "i" with a value of 0. As a result, i++ will return 1 and also save it to "i". You said it's only executing once for some reason, clearly this is part of the issue.
Check to make sure any code related to this is written as intended.
I am having trouble returning a statement when my RegExp finds no matches :
function ai(message) {
if (username.length < 3) {
username = message;
send_message("Oh, well hello " + username + ", My name is Donald J Trump and i'm a big boy");
} else {
for (i = 0; i <= botChat.length; i++) {
var re = new RegExp(botChat[i][0], "i");
if (re.test(message)) {
var length = botChat[i].length - 1;
var index = Math.ceil(length * Math.random());
var reply = botChat[i][index];
send_message(reply);
}
}
}
}
When I enter a phrase it can correctly match the first line in an array as per the for loop. The issue I'm having is when I try to add an else statement it ceases to loop through my array properly.
I have tried :
else if (re.test(message) === false) {
send_message("i can't be expected to know everything");
}
But it doesn't work, it prevents the loop from looping past botChat[0][0].
I've also tried :
if (send_message().val() == "") {
// ...
}
But every time my code no longer works. Is there a method of adding something to my array that says 'if you don't find a match above, choose this'?
Or just a way of working my code so that the if/else works?
attached is the codepen.
I checked your codepen and the lines 190 and 194 console.log(send_message().val()); seems to be breaking the loop because those lines are throwing an exception since send_message() returns undefined and undefined does not have the .val() method.
Your regular expressions are working fine. I recommend not creating new RegExp objects every iteration, instead, use the one defined in the array if (botChat[i][0].test(message)), the overhead will be less.
I'm trying to implement Heap's algorithm to find different permutations of a string and found a strange behaviour with a for loop, here's the code
function permAlone(str) {
var strArr = str.split(''),
permutations = [];
function swap(strArr, x, y) {
var tmp = strArr[x];
strArr[x] = strArr[y];
strArr[y] = tmp;
}
function generate(n) {
if (n === 1) {
permutations.push(strArr.join());
} else {
for (var i = 0; i != n; i++) {
generate(n - 1);
swap(n % 2 ? 0 : i, n - 1);
}
}
}
generate(strArr.length);
return permutations;
}
console.log(permAlone('aab'));
In the for loop within the generate function, if I put i = 0 the output of the script is ['a,a,b', 'a,a,b'] but if I put var i = 0 the output is ['a,a,b', 'a,a,b', 'a,a,b', 'a,a,b', 'a,a,b', 'a,a,b'].
I understand that var i would create a local variable for the loop, but don't understand in this case why it would change how the loop functions as there is no i variable declared anywhere else in the script.
Thanks any help appreciated.
The reason the behaviour changes if you have a global i variable is that you have multiple recursive calls to generate() all trying to control their own partially complete for loops with the same variable, and all setting i back to 0 when they start.
Picture what happens on the second iteration of the for loop: i is 1 because it has just been incremented, but then immediately a recursive call to generate() starts its own loop and sets i back to 0 again.
If you create a local variable with var then each for loop in each recursive call is independent of all the others.
Try stepping through the code with the debugger, or try adding the following as the first line inside the for loop and watch what happens to the variables when the code runs:
console.log('n:' + n + '; i: '+i);
This question is regarding Javascript for loops, where I've been having some weird behaviour.
My For loop currently looks like this:
var UnitAmount = 2;//(value verified, yet not declared like this)
var DamageAmount = [1,3];//(value verified, yet not declared like this)
function forcerefresh () {
for( i=0 ; i < UnitAmount ; i++ ) {
//(10 lines of Stuff)
var check = 0;
for (c = 0; c < DamageAmount[i] ; c++ ) {
debug[0] = damage[i][c].getElementsByClassName("writedamage")[0];
debug[1] = damage[i][c];
debug[2] = unit[i];
check = check + 1;
console.info("Unit:",i,"Loop:",c,"Debug:",debug,"Check:",check, "Race:",unitrace[i], unit[i].dataset.race);
alert("Debug:"+ debug );
damageCalc(damage[i][c].getElementsByClassName("writedamage")[0],damage[i][c],unit[i]);
}
}
}
In here, debug, alert, Check and the console write call are already added to attempt to find the problem - I'm getting an infinite loop here.
The output im getting in the console shows that while the i constant walks as intended, but the c Iteration count starts at 0, jumps to 2, and then stays 2 - and since the DamageAmount[1] = 3, this creates an infinite loop. And where the c might stick at value 2, the check values does walk up through the iterations.
As for the amount of variables involved, I've checked time and again with the console, and all of them are defined, and the values I expected. The Code is located at http://age-of-wonders-3.wikia.com/wiki/MediaWiki:Units.js, but if any parts are requested I'll of course post them here.
Any help is appreciated!
Try using for of or .forEach on an array