Jquery:for loop or $.each [duplicate] - javascript

This question already has answers here:
$().each vs $.each vs for loop in jQuery?
(3 answers)
Closed 8 years ago.
i have a doubt about the following scripts which one produce a better performance and how?
Using For Loop:
var words=$(".countryList option:selected").text().split(/ +/);
var sum=0;
var limit=14;
var appendWord="";
for(var i = 0; i < words.length; i++){
sum = sum + words[i].length;
if(sum <= limit){
appendWord = appendWord + " " + words[i];
sum = sum + 1;
}
}
Using $.each() :
var words =$(".countryList option:selected").text();
var arr = words.split(/ +/);
var textLimit=13;
var length=0;
var splittedText= '';
$.each(arr,function(i, val){
length = length + arr[i].length;
if(length <= textLimit){
splittedText = splittedText + ' ' + arr[i];
length = length + 1;
}
});
Here i get the Text from select box and tell to select box to display limited words or characters only..

Yes if we are taking about perfoemance: for loop is much faster than each .
You can verify the same using the console with date funciton that will show the curent date.

Related

Javascript Fib series test case fails

I am trying to complete this assignment for the Javascript Fibonacci series. The logic works for input 5 and 6. But the test case for 8 fails.
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out = out+ ""+ fib[i];
console.log("i is" + i + " out is" + out);
}
return out;
}
I cannot figure out what is going wrong..
It seems like things are just getting messed up with how you are adding the items to the string. Since there is no space between out + "" + fib[i], I think that would be messing with the formatting. Once i had spaces it seems to work fine, a double digit number wouldnt mess with a string like that.
function fibonacciSequence(input) {
var fib = [];
fib[0] = 0;
fib[1] = 1;
let out = ""
out+= ` ${0} `
out+= `${1}`
for (let i=2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out+= ` ${fib[i]}`
}
return out;
}
You are comparing the input (which it seems like this is maybe the number you want to stop at) to i which (plus or minus a bit) is the number of numbers in the list. You probably want to be comparing fib[i], or something like it to input to decide whether to terminate the loop.
Edit: If that's wrong and you do want input to be the number of numbers in the list, then you could just join fib at the end:
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
//var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
//out = out+ ""+ fib[i];
//console.log("i is" + i + " out is" + out);
}
return fib.join(' ');
}
for(let j = 0; j < 9; j++)
console.log('input: ' + j + ' :: ', fibonacciSequence(j));
Unless ... I've got the wrong end of the stick and #Grant Herman's answer already does what you want?

JavaScript - Printing from Array of Objects Not Working

I have this array of objects here that I am traversing and want to display a match if the person at the current index has an age within +/- 10 years of anyone else in the array. However, when I run it, it says "Cannot read property 'age' of undefined." Where did I go wrong?
function findmatches() {
var n = USERS.length;
for (var i = 0; i < n; i++) {
var currName = USERS[i].firstName;
var currAge = USERS[i].age;
var currGender = USERS[i].gender;
for (var c = 0; c < 10; c++) {
if (((USERS[c].age) + 10) <= currAge) {
document.getElementById("showmatches").innerHTML += currName + " matched to >> " + USERS[i].firstName + " " + USERS[i].lastName + " \n";
break;
}
}
}
}
What exactly is your second for loop supposed to do?
In the code you posted, it iterates through first 10 users in the USERS array. I assume it has less users than that, so at some point USERS[c] is undefined, and you're trying to access USERS[c].age.

convert javascript string to regular expression [duplicate]

This question already has answers here:
Match #(\w+) and replace in javascript
(2 answers)
Closed 6 years ago.
I have the following
function arrayInArray(chBox, values) {
try {
for (var y = 0; y < chBox.length; y++) {
var stringConcat = "/\b" + chBox[x] + ",?\b/";
var patt = new RegExp(eval(stringConcat));
console.log("value to check: " + chBox[y] + " " + values + " index " + patt.test(values));
but I can't get it to work. if I change it to this
var patt = new RegExp(/\b17,?\b/)
and then run
patt.test(values)
it works fine.
I'm passing in
var checkbox = ["17", "23"];
Can anyone tell me where I am going wrong
thanks
the code that works
for (var y = 0; y < chBox.length; y++) {
var stringConcat = "\\b" + chBox[y] + ",?\\b";
var patt = new RegExp(stringConcat);
if (patt.test(values) == false) return false;
}
There's no need for eval as its already a string. Just pass that to the RegExp constructor. You should also drop the leading and trailing / as that will be interpreted as part of the expression.

Online quiz with radio buttons having same name

I'm making a simple Quiz using Js, the problem is that my inner loop (i.e i) is not works as expected.
I have taken 3 questions and each question has 3 radio options, options of each question have same name. all the options of fist question have name='cap', options of second question name='an' and third question is name='lang'.
My js function is as follows:
function my(){
var count=0;
var totalQuestions = 3;
var correctAnswers = 0;
var alertText;
var n=["cap","an","lang"];
var j,i;
for(j=0; j<n.length; ++j){
var x = document.getElementsByName('n[j]');
for(i = 0; i < x.length; ++i){
if (x[i].checked){
if (x[i].value == 'true'){
count=count+10;
correctAnswers++;
break;
}
}
}
}
if(correctAnswers == totalQuestions){
alertText = "Congratulations! You got all the questions right!";
}
else {
alertText = "You got " + correctAnswers + " correct answers and score is " + count;
}
alert(alertText);
}
Replace line
var x = document.getElementsByName('n[j]');
to
var x = document.getElementsByName(n[j]);
That's problem because for js getElementsByName('n[y]') means "get elements with name n[y]", but not item of list n, which contain name of elements you need to select.
Good Luck !
var x = document.getElementsByName('n[j]');
Should be
var x = document.getElementsByName(n[j])
getElementsByName returns all elements that match the name per docs.
The issue is you hardcoded the string 'n[j]' so its looking for all elements with the name 'n[j]'.
You actually want to look up the name from y our array n at index j So removing the quotes will actually evaluate that expression n[j]
Change your code from
var x = document.getElementsByName('n[j]');
To
var x = document.getElementsByName(n[j]);
Your existing code tries to find a element which has name='n[j]'ie: a string. But what you want is to evaluate the expression get the element with the name equal to evaluated value.

occurences of words in an array in JavaScript [duplicate]

This question already has answers here:
How to count the number of occurrences of each item in an array? [duplicate]
(9 answers)
Closed 9 years ago.
I have an array my
array=["hello","goodbye","hello","hello","goodbye"];
and i want this array to count the occurrences of each word and print a table with each word and how many times is seen to the array in JavaScript. Can you help me please?
Try this:
var array=["hello","goodbye","hello","hello","goodbye"];
var count = {};
for (var i = 0; i < array.length; i++) {
count[array[i]] = (count[array[i]] || 0) + 1;
}
console.log(count);
HTML Output:
var table = document.createElement('table');
for (var word in count) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + word + '</td><td>' + count[word] + '</td>';
table.appendChild(tr);
}
document.body.appendChild(table);

Categories

Resources