For else loop in Javascript? - javascript
Is there a Javascript equivalent of the python 'for-else' loop, so something like this:
searched = input("Input: ");
for i in range(5):
if i==searched:
print("Search key found: ",i)
break
else:
print("Search key not found")
Or do I just have to resort to a flag variable, so something like this:
var search = function(num){
found = false;
for(var i in [0,1,2,3,4]){
if(i===num){
console.log("Match found: "+ i);
found = true;
}
}
if(!found){
console.log("No match found!");
}
};
Yes, it is possible to do this without a flag variable. You can emulate for … else statements using a label and a block:
function search(num) {
find: {
for (var i of [0,1,2,3,4]) {
if (i===num) {
console.log("Match found: "+ i);
break find;
}
} // else part after the loop:
console.log("No match found!");
}
// after loop and else
}
That said, I would recommend against doing this. It is a very unconvential way of writing this and will lead to poor understanding or confusion. An early return is acceptable though, and can be used in a helper function if you need to continue with execution after the loop.
Working example (you need to use the flag):
var search = function(num){
var found = false;
for(var i=0; i<5; i++){
if(i===num){
console.log("Match found: "+ i);
found = true;
break;
}
}
if(!found){
console.log("No match found!");
}
};
You could use Array.some(), with a testing callback:
if(!items.some( item => testCondition(item) )){
// else statement
}
Array.some() returns true if any of the elements (or tests) is true, false othewise. You can take advantage of:
before returning a truthy value, your testCondition(item) can do whatever you want.
Array.some() will stop iterating at the first truthful iteration.
Here's an example:
const findBigItem = (items) => {
if(!
// for item in items:
items.some( item => {
// here the code for your iteration
// check for the break condition
if ( item > 15) {
console.log("I broke something here: ",item);
return true; // instead of break
}
// by default return null (which is falsy)
})
) { // if no item returned true
// here goes the else statement
console.log("I found nothing!");
}
};
findBigItem([0,1,2,3,4]); //I found nothing!
findBigItem([0,10,20,30,40]); //I broke something here: 20
So Array.some() will iterate over the elements and if any returns true, the loop breaks (it won't go through the rest of the elements). At the end, the value returned by Array.some() will act as a flag: if false you run your else statement.
So the for else logic becomes if not some.
There is no built-in JavaScript equivalant.
You can emulate this by using return as a control flow. You can put your for loop in an IIFE and use the return to move beyond conditions afterwards. This does mean that vars don't pollute the scope above with variables.
(function() { // Or `(() => {` in ES6 // Python equivalent:
for (/* for loop body*/) { // for <loop body>:
if (/* Condition */) { // if <Condition>:
// Met condition // <Met condition>
return; // Goes past the else // break
} //
}//else { // else:
// Never met the condition // <Never met condition>
//}
})();
This has the advantage of not using a flag. It is now inside another function, however, so you cannot declare variables to be used outside. You can still get and set variables in the scope above, so you just have to have the var statements outside of the function.
A working example for what you wanted to do:
(function(arr, value) {
for (var i = 0, length = arr.length; i < length; i++) {
if (arr[i] === value) {
console.log("Match found: " + arr[i]);
return;
}
}//else {
console.log("No match found!");
//}
})([0, 1, 2, 3, 4], +prompt("Input: "));
If you are doing this often, you can create a function to do most of it for you.
function search(arr, condition, forBody, elseBody) {
for (var i = 0, length = arr.length; i < length; i++) {
if (condition(arr[i], arr)) { // if
return forBody(arr[i], arr); // then
}
}
return elseBody(arr); // else
}
var value = +prompt("Input: ");
search([0, 1, 2, 3, 4],
i => /* if */ i === value,
i => /* then */ console.log("Match found: " + i),
() => /* else */ console.log("No match found!"));
In these cases you can do a straight check for the value
if (!(searched in range(5))) {
console.log("No match found!");
}else{
console.log(searched + " was found!");
}
You'll have to use the boolean. There's no for-else in JavaScript.
A nice and short way to search would be to use Array.prototype.indexOf():
var search = function(num, arr){
var index = arr.indexOf(num);
if(index !== -1)
return "Match found: " + index;
}
return "No match found!";
};
Call it like this, for example:
console.log(search(4, [0,1,2,3,4]));
If your ultimate is goal is to check whether given input is there are not in an array, you can simply make use of indexOf function.
var arr = [1,2,3,4,5]
var lookingFor = 5 ;
if ( arr.indexOf(lookingFor) > -1 ) {
console.log("Input is here") ;
} else {
console.log("Nope");
}
https://jsfiddle.net/7wnasv5e/
You can either use a boolean or you can simply return. Some thing along this line should work...
var search = function(num){
found = false;
for(var i in [0,1,2,3,4]){
if(i===num){
console.log("Match found: "+ i);
return true;
}
}
return false;
};
Related
Function Returns Incorrect Value in the Middle of jQuery Each Loop
I'm getting strange behavior where I want to return immediately in the middle of a jQuery Each Loop, and my expectation is, the function below should return TRUE (the condition matches). But I'm still getting FALSE. This would have worked in Java, but doesn't work in JS/jQuery? function returnFromLoop(eventIDs) { jQuery.each(eventIDs, function(index, item) { if (item.indexOf("TEST") != -1) { return true; } }); return false; } var eventIDs = []; eventIDs.push('abc'); eventIDs.push('defTEST'); eventIDs.push('ghi'); var result = returnFromLoop(eventIDs); console.log('result = ' + result); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A return true inside jQuery's .each() method does not break out of the loop. Instead you can use return false to break out of the loop. Then, in order to capture the return value, you can use a variable. In the snippet below I have used variable returnValue. Once out of the loop, you can return that variable. From http://api.jquery.com/jQuery.each/: We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. function returnFromLoop(eventIDs) { var returnValue = false; jQuery.each(eventIDs, function(index, item) { if (item.indexOf("TEST") != -1) { returnValue = true; return false; // Equivalent to break statement. } }); return returnValue; } var eventIDs = []; eventIDs.push('abc'); eventIDs.push('defTEST'); eventIDs.push('ghi'); var result = returnFromLoop(eventIDs); console.log('result = ' + result); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The problem is you are trying to return two functions out so I used an extra variable for solution. return true act as a type of continue so you need to return false. https://stackoverflow.com/a/8224424/6517383 will help you understand more. function returnFromLoop(eventIDs) { var state = 0; jQuery.each(eventIDs, function(index, item) { if (item.indexOf("TEST") != -1) { state = 1; return 1; } }); if(state == 1) { return true; } return false; } var eventIDs = []; eventIDs.push('abc'); eventIDs.push('defTEST'); eventIDs.push('ghi'); var result = returnFromLoop(eventIDs); console.log('result = ' + result); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
how to check the presence of the element in the array?
please help solve the problem. live example is here: https://jsfiddle.net/oqc5Lw73/ i generate several tank objects: var Tank = function(id) { this.id = id; Tank.tanks.push(this); } Tank.tanks = []; for (var i = 0; i < 3; i++) { new Tank(i); } Tank.tanks.forEach(function(tank, i, arr) { console.log(tank); }); console.log('summary tanks: ' + Tank.tanks.length); after i delete tank with random index: var tankDel = Math.floor(Math.random() * (3)); Tank.tanks.splice(tankDel, 1); Tank.count -= 1; Tank.tanks.forEach(function(tank, i, arr) { console.log(tank); }); console.log('summary tanks: ' + Tank.tanks.length); i try check tanks massive. if tanks massive contain tank with property 'id' = 0 then i need display alert('tank with id 0 is dead'). but console output follow error message: Uncaught SyntaxError: Illegal break statement
break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller. See similar post here: illegal use of break statement; javascript Tank.tanks.forEach(function(tank, i, arr) { if(tank.id == 0) { tank0Dead = false; return; }; }); if(tank0Dead == true) { alert('tank with id 0 is dead'); }; jsfiddle : https://jsfiddle.net/oqc5Lw73/6/
You can't quit from forEach using break. Just remove break, and it will work. P.S: honestly, it is better to refactor that code:)
Your only problem is that you can't use the break; statement in a forEach function. But you can in a for() loop, so here is the equivalent code with a for : for (var i = 0; i < Tank.tanks.length; i++){ if (Tank.tanks[i].id == 0){ tank0Dead = false; break; } } https://jsfiddle.net/oqc5Lw73/5/ But I agree with #dimko1 about the idea of refactoring the code
You can not break a forEach callback, simply because it's a function. Here's updated working jSfiddle If you really want to break it, you can use exception like code below. try { [1,2,3].forEach(function () { if(conditionMet) { throw Error("breaking forEach"); } }); } catch(e) { } Otherwise you can use jQuery's each() method. when it's callback returns false it stops. jQuery.each([1,2,3], function () { if(conditionMet) { return false; } });
JavaScript each in grep function
I have problem using grep function. My code is var zapis = jQuery.grep(ListaGrupa, function(v, k) { console.log($(that).attr("kursid")); if (v.grupa.ID == $(that).attr("kursid")) { idZaBrisanje = v.kategorija.Id; return true; } if ($.each(v.grupa.Podgrupe, function(kljuc, vrednost) { if (vrednost.podgrupa.ID == $(that).attr("kursid")) { idZaBrisanje = vrednost.podkategorija.Id; return true; } })) return false; })[0]; But is seems return true is in each scope, so in wont affect on grep function, so I get empty results. Any help?
Yes, the return true in this case will act instruct your each function to continue the iteration. It will not break out of your grep function. Instead, you may want to set a flag, and then return false, so as to terminate the iteration: var found = false; $.each(function() { if(condition) { found = true; return false; } }); if(found) return true; Furthermore, $.each will always return the iterated object, which will always be truthy, so you can't use that inside a condition the way you're doing. This is a scenario where you may reconsider whether jQuery is actually helping you. You may consider falling back to a regular for loop here, which would allow you to return out of the grep function immediately from within the iteration. for(var i = 0; l = v.grupa.Podgrupe; i<l; i++) { var vrednost = v.grupa.Podgrupe[i]; if(condition) return true; }
forEach shows x times the rows message [duplicate]
[1,2,3].forEach(function(el) { if(el === 1) break; }); How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.
There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg. var BreakException = {}; try { [1, 2, 3].forEach(function(el) { console.log(el); if (el === 2) throw BreakException; }); } catch (e) { if (e !== BreakException) throw e; } JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it. Use Array#some Instead, use Array#some: [1, 2, 3].some(function(el) { console.log(el); return el === 2; }); This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest. some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing. Use Array#every [1, 2, 3].every(v => { if (v > 2) { return false // "break" } console.log(v); return true // must return true if doesn't break });
There is now an even better way to do this in ECMAScript2015 (aka ES6) using the new for of loop. For example, this code does not print the array elements after the number 5: const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (const el of arr) { console.log(el); if (el === 5) { break; } } From the docs: Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of an object, in original insertion order. The for...of statement iterates over data that iterable object defines to be iterated over. Need the index in the iteration? You can use Array.entries(): for (const [index, el] of arr.entries()) { if ( index === 5 ) break; }
You can use every method: [1,2,3].every(function(el) { return !(el === 1); }); ES6 [1,2,3].every( el => el !== 1 ) for old browser support use: if (!Array.prototype.every) { Array.prototype.every = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this && !fun.call(thisp, this[i], i, this)) return false; } return true; }; } more details here.
Quoting from the MDN documentation of Array.prototype.forEach(): There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead. For your code (in the question), as suggested by #bobince, use Array.prototype.some() instead. It suits very well to your usecase. Array.prototype.some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns false. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Unfortunately in this case it will be much better if you don't use forEach. Instead use a regular for loop and it will now work exactly as you would expect. var array = [1, 2, 3]; for (var i = 0; i < array.length; i++) { if (array[i] === 1){ break; } }
From your code example, it looks like Array.prototype.find is what you are looking for: Array.prototype.find() and Array.prototype.findIndex() [1, 2, 3].find(function(el) { return el === 2; }); // returns 2
Consider to use jquery's each method, since it allows to return false inside callback function: $.each(function(e, i) { if (i % 2) return false; console.log(e) }) Lodash libraries also provides takeWhile method that can be chained with map/reduce/fold etc: var users = [ { 'user': 'barney', 'active': false }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': true } ]; _.takeWhile(users, function(o) { return !o.active; }); // => objects for ['barney', 'fred'] // The `_.matches` iteratee shorthand. _.takeWhile(users, { 'user': 'barney', 'active': false }); // => objects for ['barney'] // The `_.matchesProperty` iteratee shorthand. _.takeWhile(users, ['active', false]); // => objects for ['barney', 'fred'] // The `_.property` iteratee shorthand. _.takeWhile(users, 'active'); // => []
If you would like to use Dean Edward's suggestion and throw the StopIteration error to break out of the loop without having to catch the error, you can use the following the function (originally from here): // Use a closure to prevent the global namespace from be polluted. (function() { // Define StopIteration as part of the global scope if it // isn't already defined. if(typeof StopIteration == "undefined") { StopIteration = new Error("StopIteration"); } // The original version of Array.prototype.forEach. var oldForEach = Array.prototype.forEach; // If forEach actually exists, define forEach so you can // break out of it by throwing StopIteration. Allow // other errors will be thrown as normal. if(oldForEach) { Array.prototype.forEach = function() { try { oldForEach.apply(this, [].slice.call(arguments, 0)); } catch(e) { if(e !== StopIteration) { throw e; } } }; } })(); The above code will give you the ability to run code such as the following without having to do your own try-catch clauses: // Show the contents until you get to "2". [0,1,2,3,4].forEach(function(val) { if(val == 2) throw StopIteration; alert(val); }); One important thing to remember is that this will only update the Array.prototype.forEach function if it already exists. If it doesn't exist already, it will not modify the it.
Short answer: use for...break for this or change your code to avoid breaking of forEach. Do not use .some() or .every() to emulate for...break. Rewrite your code to avoid for...break loop, or use for...break. Every time you use these methods as for...break alternative God kills kitten. Long answer: .some() and .every() both return boolean value, .some() returns true if there any element for which passed function returns true, every returns false if there any element for which passed function returns false. This is what that functions mean. Using functions for what they doesn't mean is much worse then using tables for layout instead of CSS, because it frustrates everybody who reads your code. Also, the only possible way to use these methods as for...break alternative is to make side-effects (change some vars outside of .some() callback function), and this is not much different from for...break. So, using .some() or .every() as for...break loop alternative isn't free of side effects, this isn't much cleaner then for...break, this is frustrating, so this isn't better. You can always rewrite your code so that there will be no need in for...break. You can filter array using .filter(), you can split array using .slice() and so on, then use .forEach() or .map() for that part of array.
As mentioned before, you can't break .forEach(). Here's a slightly more modern way of doing a foreach with ES6 Iterators. Allows you to get direct access to index/value when iterating. const array = ['one', 'two', 'three']; for (const [index, val] of array.entries()) { console.log('item:', { index, val }); if (index === 1) { console.log('break!'); break; } } Output: item: { index: 0, val: 'one' } item: { index: 1, val: 'two' } break! Links Array.prototype.entries() Iterators and generators Destructuring assignment
Another concept I came up with: function forEach(array, cb) { var shouldBreak; function _break() { shouldBreak = true; } for (var i = 0, bound = array.length; i < bound; ++i) { if (shouldBreak) { break; } cb(array[i], i, array, _break); } } // Usage forEach(['a','b','c','d','e','f'], function (char, i, array, _break) { console.log(i, char); if (i === 2) { _break(); } });
This is just something I came up with to solve the problem... I'm pretty sure it fixes the problem that the original asker had: Array.prototype.each = function(callback){ if(!callback) return false; for(var i=0; i<this.length; i++){ if(callback(this[i], i) == false) break; } }; And then you would call it by using: var myarray = [1,2,3]; myarray.each(function(item, index){ // do something with the item // if(item != somecondition) return false; }); Returning false inside the callback function will cause a break. Let me know if that doesn't actually work.
If you don't need to access your array after iteration you can bail out by setting the array's length to 0. If you do still need it after your iteration you could clone it using slice.. [1,3,4,5,6,7,8,244,3,5,2].forEach(function (item, index, arr) { if (index === 3) arr.length = 0; }); Or with a clone: var x = [1,3,4,5,6,7,8,244,3,5,2]; x.slice().forEach(function (item, index, arr) { if (index === 3) arr.length = 0; }); Which is a far better solution then throwing random errors in your code.
Found this solution on another site. You can wrap the forEach in a try / catch scenario. if(typeof StopIteration == "undefined") { StopIteration = new Error("StopIteration"); } try { [1,2,3].forEach(function(el){ alert(el); if(el === 1) throw StopIteration; }); } catch(error) { if(error != StopIteration) throw error; } More details here: http://dean.edwards.name/weblog/2006/07/enum/
This is a for loop, but maintains the object reference in the loop just like a forEach() but you can break out. var arr = [1,2,3]; for (var i = 0, el; el = arr[i]; i++) { if(el === 1) break; }
try with "find" : var myCategories = [ {category: "start", name: "Start", color: "#AC193D"}, {category: "action", name: "Action", color: "#8C0095"}, {category: "exit", name: "Exit", color: "#008A00"} ]; function findCategory(category) { return myCategories.find(function(element) { return element.category === category; }); } console.log(findCategory("start")); // output: { category: "start", name: "Start", color: "#AC193D" }
Yet another approach: var wageType = types.filter(function(element){ if(e.params.data.text == element.name){ return element; } }); console.dir(wageType);
I use nullhack for that purpose, it tries to access property of null, which is an error: try { [1,2,3,4,5] .forEach( function ( val, idx, arr ) { if ( val == 3 ) null.NULLBREAK; } ); } catch (e) { // e <=> TypeError: null has no properties } //
Use the array.prototype.every function, which provide you the utility to break the looping. See example here Javascript documentation on Mozilla developer network
Agree with #bobince, upvoted. Also, FYI: Prototype.js has something for this purpose: <script type="text/javascript"> $$('a').each(function(el, idx) { if ( /* break condition */ ) throw $break; // do something }); </script> $break will be catched and handled by Prototype.js internally, breaking the "each" cycle but not generating external errors. See Prototype.JS API for details. jQuery also has a way, just return false in the handler to break the loop early: <script type="text/javascript"> jQuery('a').each( function(idx) { if ( /* break condition */ ) return false; // do something }); </script> See jQuery API for details.
If you want to keep your forEach syntax, this is a way to keep it efficient (although not as good as a regular for loop). Check immediately for a variable that knows if you want to break out of the loop. This example uses a anonymous function for creating a function scope around the forEach which you need to store the done information. (function(){ var element = document.getElementById('printed-result'); var done = false; [1,2,3,4].forEach(function(item){ if(done){ return; } var text = document.createTextNode(item); element.appendChild(text); if (item === 2){ done = true; return; } }); })(); <div id="printed-result"></div> My two cents.
If you need to break based on the value of elements that are already in your array as in your case (i.e. if break condition does not depend on run-time variable that may change after array is assigned its element values) you could also use combination of slice() and indexOf() as follows. If you need to break when forEach reaches 'Apple' you can use var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var fruitsToLoop = fruits.slice(0, fruits.indexOf("Apple")); // fruitsToLoop = Banana,Orange,Lemon fruitsToLoop.forEach(function(el) { // no need to break }); As stated in W3Schools.com the slice() method returns the selected elements in an array, as a new array object. The original array will not be changed. See it in JSFiddle Hope it helps someone.
Why don't you try wrapping the function in a Promise? The only reason I bring it up is that I am using a function in an API that acts in a similar manner to forEach. I don't want it to keep iterating once it finds a value, and I need to return something so I am simply going to resolve a Promise and do it that way. traverseTree(doc): Promise<any> { return new Promise<any>((resolve, reject) => { this.gridOptions.api.forEachNode((node, index) => { //the above function is the one I want to short circuit. if(node.data.id === doc.id) { return resolve(node); } }); }); } Then all you need to do is do something with the result like this.traverseTree(doc).then((result) => { this.doSomething(result); }); My above example is in typescript, simply ignore the types. The logic should hopefully help you "break" out of your loop.
This isn't the most efficient, since you still cycle all the elements, but I thought it might be worth considering the very simple: let keepGoing = true; things.forEach( (thing) => { if (noMore) keepGoing = false; if (keepGoing) { // do things with thing } });
you can follow the code below which works for me: var loopStop = false; YOUR_ARRAY.forEach(function loop(){ if(loopStop){ return; } if(condition){ loopStop = true; } });
Breaking out of built-in Array.prototype.map function esp in React The key thing to note here is the use of statement return to BREAK let isBroken = false; colours.map(item => { if (isBroken) { return; } if (item.startsWith("y")) { console.log("The yessiest colour!"); isBroken = true; return; } }); More information here: https://www.codegrepper.com/code-examples/javascript/break+out+of+map+javascript
I know it not right way. It is not break the loop. It is a Jugad let result = true; [1, 2, 3].forEach(function(el) { if(result){ console.log(el); if (el === 2){ result = false; } } });
You can create a variant of forEach that allows for break, continue, return, and even async/await: (example written in TypeScript) export type LoopControlOp = "break" | "continue" | ["return", any]; export type LoopFunc<T> = (value: T, index: number, array: T[])=>LoopControlOp; Array.prototype.ForEach = function ForEach<T>(this: T[], func: LoopFunc<T>) { for (let i = 0; i < this.length; i++) { const controlOp = func(this[i], i, this); if (controlOp == "break") break; if (controlOp == "continue") continue; if (controlOp instanceof Array) return controlOp[1]; } }; // this variant lets you use async/await in the loop-func, with the loop "awaiting" for each entry Array.prototype.ForEachAsync = async function ForEachAsync<T>(this: T[], func: LoopFunc<T>) { for (let i = 0; i < this.length; i++) { const controlOp = await func(this[i], i, this); if (controlOp == "break") break; if (controlOp == "continue") continue; if (controlOp instanceof Array) return controlOp[1]; } }; Usage: function GetCoffee() { const cancelReason = peopleOnStreet.ForEach((person, index)=> { if (index == 0) return "continue"; if (person.type == "friend") return "break"; if (person.type == "boss") return ["return", "nevermind"]; }); if (cancelReason) console.log("Coffee canceled because: " + cancelReason); }
I use return false and it works for me.
const Book = {"Titles":[ {"Book3" : "BULLETIN 3"}, {"Book1" : "BULLETIN 1"}, {"Book2" : "BULLETIN 2"} ]} const findbystr = function(str) { Book.Titles.forEach(function(data) { if (typeof data[str] != 'undefined') { return data[str]; } }, str) } book = findbystr('Book1'); console.log(book);
How to accomplish this without using eval
Sorry for the title but I don't know how to explain it. The function takes an URI, eg: /foo/bar/1293. The object will, in case it exists, be stored in an object looking like {foo: { bar: { 1293: 'content...' }}}. The function iterates through the directories in the URI and checks that the path isn't undefined and meanwhile builds up a string with the code that later on gets called using eval(). The string containing the code will look something like delete memory["foo"]["bar"]["1293"] Is there any other way I can accomplish this? Maybe store the saved content in something other than an ordinary object? remove : function(uri) { if(uri == '/') { this.flush(); return true; } else { var parts = trimSlashes(uri).split('/'), memRef = memory, found = true, evalCode = 'delete memory'; parts.forEach(function(dir, i) { if( memRef[dir] !== undefined ) { memRef = memRef[dir]; evalCode += '["'+dir+'"]'; } else { found = false; return false; } if(i == (parts.length - 1)) { try { eval( evalCode ); } catch(e) { console.log(e); found = false; } } }); return found; } }
No need for eval here. Just drill down like you are and delete the property at the end: parts.forEach(function(dir, i) { if( memRef[dir] !== undefined ) { if(i == (parts.length - 1)) { // delete it on the last iteration delete memRef[dir]; } else { // drill down memRef = memRef[dir]; } } else { found = false; return false; } });
You just need a helper function which takes a Array and a object and does: function delete_helper(obj, path) { for(var i = 0, l=path.length-1; i<l; i++) { obj = obj[path[i]]; } delete obj[path.length-1]; } and instead of building up a code string, append the names to a Array and then call this instead of the eval. This code assumes that the checks to whether the path exists have already been done as they would be in that usage.