Iterating through all the instances with name having a common string [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Is there a way to access all the object instances starting with a common string.
Example: I have instances named button64, button223, button856471, button229846, etc. I have no control over how these instances are named. I want to push all these in an array.
I am not creating these objects, I just have to write a javascript which sits in this HTML page and collects all the object instances starting with the string 'button'.
The purpose is to reach out to a desired object out of these and change the visual element.
Also, the solution has to be compatible with IE8. Any ideas about how should I iterate?

If you can use jQuery, you could write:
var buttonsArray = [];
$("div").each(function() {
var id = $(this).attr("id");
if (id && id.indexOf("button") == 0) {
buttonsArray.push($(this));
}
});

You can use regular expressions to find any expression matching the pattern. Using the match method, every instance of the pattern is returned as an array.
var str = document.getElementById("sample");
var arr = string.match(/button[\d]*/g);
The regular expression on line two will match any result that has "button" and will stop once it encounters a character afterwards that is not a digit.

Related

Is there a way that this is possible? I am trying to find a value of a var constructed by other variables [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
This is a little bit of my code. I took out the complex parts. It is all on the script tag.
var trueenemyscoutx = '_2'
var tryeenemyscouty = '2'
var type_22 = "none"
var move1;
enemymove = "type" + trueenemyscoutx + trueenemyscouty;
var move1 = (enemymove.valueOf()).valueOf()
In the post, enemymove is a string constructed by concatenating "type" and two other variables, each of which is also a string.
The resultant string contains no information about the variables used and so the general answer to the question is no, it is not possible using the approach taken.
Obvious alternatives include:
Keep move a string, but use a separator (e.g. colon, comma or space) between component substrings. This allows extracting an array of the components using move.split(separator).
Use an array or simple object to hold move information instead of a string in the first place.

Most efficient/faster way of checking if string belongs to array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to find the most efficient/fastest way of checking if a string belongs in an array in both Java and JavaScript. For example, I want to find if the string "=" belongs in the array {"+", "-", "=", "*", "/", "!"}
A way to do it in Java is(omitting the main method)
String[] symbols = {"+", "-", "=", "*", "/", "!"};
String equalTo = "=";
for(String i: symbols) {
if(equalTo.equals(i)) {
System.out.print(equalTo + " belongs to symbols.");
}
}
I would like to know if there is a single method which does this work for me in either Java and JavaScript.
The reason I am asking this in both languages is that I want to see if it is easier in Java or JavaScript.
Answers for your question in JavaScript: How do I check if an array includes an object in JavaScript?
E.g. If you search for full match you can use:
["=", "+", "-"].indexOf("=") // => 1
The most efficient way to see if a string is in a collection of strings, is when this collection is already hashed. For example, if you have a HashSet<String> in Java, you can just use the .contains(String) method, which runs in O(1).
If your collection is stored as a ArrayList<String> or array, it takes O(n) time to check if a string is in the collection (also with the .contains(String) method).
Turning a list or array into a set takes O(n) time, but takes longer than checking if a single element is in the list.
So, in conclusion:
If you only want to check for one element if it's in the collection, just iterate over the list that you apparently already have, and check if the element is in the list. For an array, in Java simply use Arrays.asList(symbols).contains(equalTo) and in JavaScript use symbols.contains(equalTo)
If you want to check for a lot of elements whether they are in the collection, then it's better to turn the collection into a set first. In Java, do something like
HashSet<String> set = new HashSet<String>();
set.addAll(Arrays.asList(symbols));
after which you can do set.contains(equalTo).
For JavaScript, that's a little more annoying, but the first thing off the top of my head is like this:
var set = Object.create(null);
for (var i in symbols) {
set[i] = true;
}
Then, you can check if checkTo in set.
Sorry for long answer, but you asked for efficiency right?
In Java you can use Arrays.asList(yourArray).contains(yourValue). If you use jQuery you can use $.inArray(yourValue, yourArray).
The "best" way to do it really depends on the number of values to match against and how often you need to do it.
If the list is long, and you do it often, you'd be better served by creating a set/map/associate-array for fast lookup, or sort the list of values and perform a binary search. In Java, that would be Set<String> or Arrays.binarySearch().
However, in your case the list is short, so a sequential search like you're doing is fine.
But in addition to that, your values are all single-character, so there is a solution that just happens to be the exact same solution for both Java and JavaScript: indexOf()
In Java:
if ("+-=*/!".indexOf(value) != -1) {
// found
}
In JavaScript:
if ("+-=*/!".indexOf(value) != -1) {
// found
}
Eerie, huh?

Is this eval Evil? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Writing a function in JavaScript. The plan is the function creates an object, which requires boolean statements as parameters. Something like this ->
var foo = new fuzz("pie < squirrel", "monkey === banana");
My question is - Is this evil?
*Note - * Inside the function 'fuzz' I will run checks on the values of the parameters. (Check string.length etc). I think this is how one is meant to use eval, it just has such a bad reputation on t'up web.
Thanks
Summing up the conclusions in the comments: write a simple rule evaluation engine! E.g.:
var variables = { ... };
function niceEval(condition) {
var operands = condition.match(/(\w+)\s+(\S+)\s+(\w+)/);
switch (operands[2]) {
case '<' :
return variables[operands[1]] < variables[operands[3]];
...
}
}
This also gives you a lot more control over possibly occurring errors than blindly evaling a string.

Get the value of a div [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Helllo, I'm having a div like this:
<div>1+1</div>
How can I get these '1+1' to the javascript and calculate them to '2'?
Thanks in advance!
you can use innerHTML property of element by javascript to extract the value:
document.getElementById("div").innerHTML
and then use eval() method to evaluate the math expression:
var exp=document.getElementById("div").innerHTML;
alert(eval(exp));
You need to somehow identify this div, e.g
<div id="div-with-expression">1+1</div>
And code will be like:
console.log(eval(document.getElementById('div-with-expression').innerText));
You can use eval:
var equation = getElementById(IdOfDiv).innerHTML;
var result = eval(equation);
Well, You could use the Javascript eval() func:
http://www.w3schools.com/jsref/jsref_eval.asp
But, eval functions can introduce malicious code into your environment.
I'm not sure as to what your purpose to start with and what your assumptions are for that input but here's another way to go about it with regex although it's more complicated:
var myRegexp = /(\d+)(\+)(\d+)/;
var match = myRegexp.exec("1+1");
// parseInt(match[0]) == 1 ,as an Int
// match[1] = '+', you could figure what operand this is with 'if else' conditions
// parseInt(match[2]) == 1 ,as an Int

creating DOM nodes from arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Note: This is a continuation of another question that I decided were two separate issues that need to be solved. I'm also currently not sure of how exactly to phrase this question, so I will try my best and when I get more clarity I will rephrase my question for future reference.
I'm writing two basic jQuery plugins, $.fn.query and $.fn.build, that sort an array, and create html code to insert into a document, respectively. I'm currently testing it with Vimeo video ID's that I will display videos with.
$.fn.build has three parts. First it wraps every array item with individual containers, the builds them into rows (problem area), then lastly it wraps everything in a container. (every part of this is optional).
Specifically the problem comes from this line: $(tmp).add(newRow); although it is valid javascript.
if ( options.splitBy !== undefined && options.wrapRow !== undefined ) {
var tmp = $([]),
newRow = function(i) {
$(build.splice( i, i + options.splitBy )).wrapAll( options.wrapRow ).parent();
};
for (var i = 0, l = build.length, a = options.splitBy; i < l; i += a) {
$(tmp).add(newRow);
}
build = tmp;
console.log(build);
}
See: http://jsbin.com/upatus/2/edit
I am quite sure that you want to use the function, instead of adding the function itself. Also, you will want to use the same tmp object all over the time, instead of wrapping it into a new jQuery instance and not adding to the original one. Try
tmp.add(newRow(i));
BTW: If you want to build an array, you should use
var tmp = [];
and
tmp.push(…);
Now I've looked at the code from the other question. Both answers are correct, and contain some valid points:
splice is an Array function on jQuery's prototype, and returns an array. (You have fiexd this now)
Your query method returns an array, but should return a jQuery instance for chaining
Your build variable was not initialized, but used
You should really choose whether you want to use arrays or jQuery objects internally in your function, and not mix them.
BTW, you should rename your functions to more descriptive names. "build" and "query" are very vague and may collide with other plugins.

Categories

Resources