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 5 years ago.
Improve this question
var sunny=[1,2,3];
var bunny=[4,5,6];
var name=prompt("Enter Name");
for(var i=0;i<3;i++)
{
document.write(name[i]);
}
//If User input Sunny then array elements of sunny will be printed.
You can use object for users and write your users in it, example:
var users = {
sunny: [1,2,3],
bunny: [4,5,6]
}
var name = prompt("Enter Name");
console.log(users[name]);
//If User input Sunny then array elements of sunny will be printed.
I think what you want is to use an object:
const names = {
sunny:[1,2,3],
bunny:[4,5,6],
};
const name=prompt("Enter Name");
for(var i=0;i<3;i++)
{
document.write(names[name][i]);
}
There is not clean way to get a variable if you have its name as string. However its easy to access an objects properties with a string with the [] syntax.
U can achieve this by using 'eval'.
See the update code.
var sunny=[1,2,3];
var bunny=[4,5,6];
var name=prompt("Enter Name");
for(var i=0;i<3;i++)
{
document.write(eval(name)[i]);
}
You can use a switch-statement (https://www.w3schools.com/js/js_switch.asp) like
var a;
switch(name) {
case "sunny":
a = sunny;
break;
case "bunny":
a = bunny;
break;
}
for(var i = 0; i < a.length; i++) {
document.write(a[i]);
}
Related
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 4 years ago.
Improve this question
[Ask]
anyone know the reference for a case like this?
the user must type the word: "learn" -> total character 5
while the user types instead: "l3arn"
well I want to count the right word only, so the result 4
from google not yet find a solution, maybe someone knows the keyword/reference for the problem.
I want to implement it in javascript
You want to calculate the number of characters in the correct position?
In that case, it's a simple solution.
Javascript example:
function countCorrectCharacters(expectedString, string) {
var count = 0;
var l = Math.min(expectedString.length, string.length);
for (var i = 0; i < l; ++i) {
if (expectedString[i] === string[i]) {
++count;
}
}
return count;
}
var str = "learn";
var userInput = "l3arn";
var userInputArray = userInput.split('');
var counter = 0;
for(var i = 0; i< "l3arn".lenth(); i++){
if(str.indexOf(userInputArray[i]) !== -1) counter++;
}
If I understand correctly you want to count the number of letters in a string? Use this:
function getNumberOfLetters(string) {
let match = string.match(/[A-Za-z]/g);
return (match && match.length) || 0;
}
console.log(getNumberOfLetters("learn")); // 5
console.log(getNumberOfLetters("l3arn")); // 4
console.log(getNumberOfLetters("12345")); // 0
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 6 years ago.
Improve this question
I have an array within an angular scope that basically contains an object within each iteration. I have used the indexOf() function before to check if a value exists within an array - but how can I check if a value exists within the object word value?
I want to use a foreach loop and just check if a word exists within the rules array in the format shown below - how is the best way to achieve this?
rules = [];
rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}
rules = []
rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}
rules[3] = { sentence:"horse"}
rules.forEach(rule => {
if (rule.word) {
console.log('Exist. Value:', rule.word)
} else {
console.log('Doesn\'t Exist.')
}
})
Hope this helps!
for(var i =0;i < rules.length;i++){
if(rules[i].word === 'valueYouWantToCheck'){
// do whatever you want to do
}
}
Try this...:)
You can use this
var rules = [];
rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}
rules.forEach(function(item){
console.log(item.word) // your word of choice
})
You can also use filter function. If your required word is matched it will return the object or else it will return an empty array
var getValue = rules.filter(function(item){
return item.word=='house';
})
console.log(getValue)
Beside you can also use .find method
rules.find(function(item){
return item.word=="house";
})
rules = [];
rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}
for(var i=0; i<rules.length ; i++)
{
rules[i]["word"]=='valueforComparison'; // or rules[i].word=='valueforComparison';
}
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 9 years ago.
Improve this question
to say some space and repetition I'm trying to use a var n to store a common location for a folder but also want to later combine a image name.
example.
var n="/me/work/air/image/";
var get_images = ["'+n+'" "1.jpg"",n+ "2.jpg" ]
I'm simply just trying to include var n with the string "1.jpg"
so the result would be
"/me/work/air/image/1.jpg","/me/work/air/image/2.jpg"
Are you looking for something like this?
var n= "/me/work/air/image/";
var get_images = [];
for (var i=0; i < 30; i++) {
get_images.push(n + "" + i + ".jpg");
}
this while loop is prolly the fastest one... length is the number of images ..
var path='/me/work/air/image/',length=10,array=[];
while(length--){
array[length]=path+length+'.jpg'
}
array.shift() // if you start from 1
or just create a function where i is the number of the image
function getImg(i){
return '/me/work/air/image/'+i+'.jpg'
}
use
var image1=getImg(1);
or
'<img src="'+getImg(1)+'">'
it also all depends inwhich contest you wanna reuse the image later and how often
Try this
var n= "/me/work/air/image/";
var get_images = {
first: n + "1.jpg",
second: n+ "2.jpg"
};
Now you can use get_Images["first"] or get_Images.first to get the data of each properties of JSON object.
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
var makeModelYearSelect = document.getElementById("<%= MakeModelYearFilterLB.ClientID %>").control;
var selectedMakeModelYearItems = makeModelYearSelect.get_checkedItems();
var selectedMakeModelYearItemIds = [];
for (var index = 0; index < selectedMakeModelYearItems.length; index++) {
selectedMakeModelYearItemIds.push(selectedMakeModelYearItem[index].get_value(index));
}
Why is this firing back an error of Microsoft JScript runtime error: 'selectedMakeModelYearItem' is undefined?
Mootools won't let me use a simple for...in for iterations.
I've looked at it 6 ways to Sunday so what the heck am I missing?
Because selectedMakeModelYearItem is undefined.
selectedMakeModelYearItems isn't, though.
Maybe you try to call this code berofe page is loaded. In this case select tag that you try to access don't rendered and cannot be accessed from JavaScript. You can try something like
window.addEventListener("load",
(function() {
return function setMakeModelYearFilter() {
var makeModelYearSelect = document.getElementById("<%= MakeModelYearFilterLB.ClientID %>").control;
var selectedMakeModelYearItems = makeModelYearSelect.get_checkedItems();
var selectedMakeModelYearItemIds = [];
for (var index = 0; index < selectedMakeModelYearItems.length; index++) {
selectedMakeModelYearItemIds.push(selectedMakeModelYearItem[index].get_value(index));
}
window.removeEventListener('load', setMakeModelYearFilter, false);
}})()
, false);
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Sometimes you have a function that will work for flat arguments. For example:
send(player,message)
But what if, instead, you have collections of players / messages?
message = ['Welcome!','Check our site for events.']
players = [Player1,Player2,Player3]
Writting for-loops will reduce readability and won't work if you don't know statically if your argument is a collection or object. Rewritting the function is sometimes not viable or too laborous and promotes duplicate code. What is a simplier solution?
You can write a decorator that will transform your function into a function that will take the cartesian product of it's own arguments and call the original function on it.
function send(player,message) {
console.log('To ',player,': ',message);
}
cartesian(send)(['Player1','Player2','Player3'],['Welcome!','Check our site.']);
//Output:
//To Player1 : Welcome!
//To Player1 : Check our site.
//To Player2 : Welcome!
//To Player2 : Check our site.
//To Player3 : Welcome!
//To Player3 : Check our site.
This implements the decorator ("cartesian") on Javascript:
function cartesian_product(arr){
//cartesian_product( [[1,2],[3,4]] ) = [[1,3],[1,3],[2,3],[2,4]]
function partial_product(arr,i){
//partial_product([[1,2],3],0) = [[1,3],[2,3]]
var result = []
for (j=0; j<arr[i].length; ++j){
arr_changed = arr.slice();
arr_changed.splice(i,1,arr[i][j]);
result.push(arr_changed);
};
return result;
};
var result = [arr.slice()];
for (var x=0; x<arr.length; ++x){
for (var y=0; y<result.length; ++y){
if (result[y][x] instanceof Array) {
result.splice.apply(result,[y,1].concat(partial_product(result[y],x)));
}
}
}
return result;
};
function cartesian(func){
//cartesian(func)([1,2],[3,4]) = [func([1,3]),func([1,4]),func([2,3]),func([2,4])]
_this = this;
return function(){
var args_list = cartesian_product(Array.prototype.slice.call(arguments));
var return_values = []
for (var i=0; i<args_list.length; ++i){
return_values.push(func.apply(_this,args_list[i]))
}
return return_values;
}
}