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
I have an array likes this
<script>
var myFruit = new Array("Apple", "orange", "banana", "plum", "pear");
var myindex = prompt("enter 0 to 4","");
document.write(myFruit[myindex]);
</script>
It will prompt a window and user enter a number then get result.
Now I don't want a prompt, I want to display the fruit in order like: My 1 fruit is an Aplle.
How can I write a code so that when I enter 1, then it will show: My 1 fruit is an (image) Apple. When I enter 2, it will show: My 2 fruit is an (image) orange....
I don't know how to get the index changed, then it will show both index and value simultaneously.
Please give me a hand . Thanks
------------------------------------------------------
From the help of user2782160, I have another concern below
I have 5 images put in an array likes this
<script>
var myDegree = new Array("30.gif", "60.gif", "90.gif", "120.gif", "150.gif");
.........
</script>
I need to write code somehow to have
<div id="degreeCount"> 30</div><div>//image 30.gif has to show inside this div</div>
I mean 30.gif will show next to the number 30.
Please give me a hand. Thank you!
Just concatenate the strings:
var myindex = parseInt(prompt("enter 0 to 4", ""), 10);
document.write ('My ' + myindex + ' fruit is an ' + myFruit[myindex]);
something like this i guess?
for(i = 0; i<myFruit.length; i++){
document.write("My "+i+" fruit is an <img src='URL HERE MINUS FRUIT NAME'"+myFruit[i]+".jpg>");
}
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
I have a an array of product names like:
Big Bottle 500ml
Big Bottle 1l
Big Bottle 2l
I want to remove the duplicated first part of the string in JavaScript to produce an array like:
500ml
1l
2l
The Product names can be anything i.e. Tub 8oz but will always have duplication/the same prefix at the start
Not sure where to start with this regex or maybe a loop that compares each character until it hits a missmatch
Since you said but will always have duplication at the start so you can try following
Get the string to remove from the first element and then loop through all the elements to remove that string
let arr1 = ['Big Bottle 500ml', 'Big Bottle 1l', 'Big Bottle 2l']
let arr2 = ['Bottle 500ml', 'Bottle 1l', 'Bottle 2l']
function getData(arr) {
let strToRemove = arr[0].match(/\D+/)[0]
return arr.map(d => d.replace(strToRemove, '').trim())
}
console.log(getData(arr1))
console.log(getData(arr2))
If your format will always be Name Name Name ... XXXunit. You can easily split the string with the space delimiter. It doesn't really detect any duplicates, but based on your post, it sounds like youre just trynna get the value and unit
const data = ['Tub 500ml', 'Tub 450ml', 'Small Can 200ml', 'Big Ass Bottle 999ml', 'Artificial Rain Tank V99.55 5500.50L'];
const result = [];
data.forEach(function(item){
const splitted = item.split(" ");
result.push(splitted[splitted.length - 1]);
})
console.log(result)
Using Array#reduce() to walk through all the characters to find the common starting string then map() to remove it
const prods = ['Big Bottle 500ml','Big Bottle 1l','Big Bottle 2l'];
const dupStr = [...prods[0]].reduce((a, c) => {
return prods.every(s => s.startsWith(a + c)) ? a + c : a;
}, '')
const res = prods.map(s => s.replace(dupStr, '').trim())
console.log(`common string :: "${dupStr}"`)
console.log('results ::\n',res)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I've written a script that takes grades from a user for different units and then adds them to an array, shows the grades and also an average.
When I run the script it works fine, but instead of an average, it displays 'grade' is not defined.
var subjects = ["CF:", "DaD:", "PoP:", "N&CS:", "SAD:", "APP:"];
var grades = ["", "", "", "", "", ""];
var result;
grades[0] = prompt("Please enter your marks for CF: ");
grades[1] = prompt("Please enter your marks for DaD: ");
grades[2] = prompt("Please enter your marks for PoP: ");
grades[3] = prompt("Please enter your marks for N&CS: ");
grades[4] = prompt("Please enter your marks for SAD: ");
grades[5] = prompt("Please enter your marks for APP: ");
console.log("Units and grades are: ");
console.log(subjects[0] +"\t"+ grades[0] );
console.log(subjects[1] +"\t"+ grades[1] );
console.log(subjects[2] +"\t"+ grades[2] );
console.log(subjects[3] +"\t"+ grades[3] );
console.log(subjects[4] +"\t"+ grades[4] );
console.log(subjects[5] +"\t"+ grades[5] );
result = grades[0] + grades[1] + grades[2] + grades[3] + grades[4] +
grade[5];
console.log("Average: " + "\t" + result / 6);
anyone have any ideas?
Apologies for the bad javascript, i'm very new to this.
In this code,
result = grades[0] + grades[1] + grades[2] + grades[3] + grades[4] + grade[5];
grade[5] must be grades[5]. You missed "s" point.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Is there a function in Java Script that divide a string with several arguments?
var string = "This is a test text, again, this is a testing text";
For example, I can split with , by saying string.split(','); and I will have:
var string = ["This is a test text", "again", "this is a testing text"];
Now, I want to split it with several parameters, so string now would be
var string = ["test text", "testing text"]
I'm looking for a function that extract all the parts that start with test and end with text.
I'm not sure that I understood what you want, but here is a function I wrote in 2 minutes. With the following scenario
var string = "This is a test text, again, this is a testing text";
function customSplit(str_to_split, start_string, end_string) {
var res = [];
var start_index, end_index;
for (i = 0; i <= str_to_split.length; i++) {
start_index = str_to_split.toLowerCase().indexOf(start_string.toLowerCase(), i);
if (i == start_index) {
end_index = str_to_split.toLowerCase().indexOf(end_string.toLowerCase(), i);
if (end_index >= 0) {
res.push(str_to_split.substring(start_index, end_index + end_string.length));
}
}
}
return res;
}
console.log(customSplit(string, "test", "text"));
it will output ["test text", "testing text"].
Let me know if it helps you.
EDIT
Corrected a wrong behave with a particular string. Please remind that I wrote it in a couple of minutes.
Use a regex:
var str = "This is a test text, again, this is a testing text";
console.log(str.match(/test.+?text/g));
So I am trying to make a javascript game for my geography class but I have run into some trouble, I can ask the questions and tell you if you're wrong or not but I would like to be able to keep track of the wrongs answers. I want to keep track using for loops but I'm not good at them, some help would be greatly appreciated!
This is the basis of what every question looks like, it's just that && is where I need to add a single mark to the incorrect tally which I am sure I need to use for loops for.
var y = "You are correct!!!"
var n = "You are incorrect!!!"
alert("Chapter 1, Human Cultural Connections. 1-10")
//==================================================
var Q1 = prompt("Demographers identify three different stages of life.
They are children, working adults, and older adults. What is the age
range for children? 0-13, 0-15, 0-18")
if (Q1 === "0-13")
{
alert(y)
}
else
{
alert(n) //&& add 1 tally to incorrect list
}
If someone could help me out with this it would be sooo helpful, and don't worry this is past do anyways but I still want to know how to do it for future projects!
p.s. I already have the script HTML so I don't need help with that.
var correct = [], // well store the index of the correctly answered questions here
wrong = [], // well store the index of the incorrectly answered questions here
questions = [
{
"question": "Demographers identify three different stages of life. They are children, working adults, and older adults. What is the age range for children?",
"answers": ["0-13", "0-15", "0-18"],
"correct": 0 // correct answer is item of index 0 in property "answers" (0-13)
},
{
"question": "whats your favorite color?",
"answers": ["red", "yellow", "blue", "purple"],
"correct": 2 // blue
}
];
for (var i in questions){
var answer = prompt(questions[i].question + questions[i].answers.join(','));
if (answer == questions[i].answers[questions[i].correct]){
correct.push(i);
}else{
wrong.push(i);
}
}
alert('wrong number of answers: ' + wrong.length);
alert('correct number of answers: ' + correct.length);
alert('first wrong question: ' + questions[wrong[0]].question);
I know this is practically overwngineering what you asked for but it might give you better flexibility and knowledge as to how js for loops work. Hope it helps.
Add a variable to keep track of incorrect answers:
var y = "You are correct!!!"
var n = "You are incorrect!!!"
var incorrectCount = 0;
alert("Chapter 1, Human Cultural Connections. 1-10")
//==================================================
var Q1 = prompt("Demographers identify three different stages of life.
They are children, working adults, and older adults. What is the age
range for children? 0-13, 0-15, 0-18")
if (Q1 === "0-13")
{
alert(y)
}
else
{
alert(n) //&& add 1 tally to incorrect list
incorrectCount++;
}
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 8 years ago.
Improve this question
I'm new to query/javascript and having a problem with the following code to calculate a gross value and tax amount based
on the net amount the user enters. The user will enter a double amount and the gross and vat amounts are also defined as doubles.
Can anyone help? I get an error: "Uncaught SyntaxError: Unexpected number" when i try running the following code.
$('#netPayment').change(calcLowerVatRateAndGrossAmount);
/* $('#netPayment').change(function(){
calcLowerVatRateAndGrossAmount();
}); */
});
function calcVatRateAndGrossAmount(){
var netPayment = parseFloat($('#netPayment').val());
var vatAmount = 00.0;
var VatRate = 20.0;
var grossPayment = 0.00;
var totalPaymentAmount = 0.00;
if (netPayment !== '') {
vatAmount = (netPayment * VatRate) / 100;
grossPayment = (netPayment - vatAmount);
$('#vatAmount').val(parseFloat(vatAmount.data).toFixed(2));
$('#grossPayment').val(parseFloat(grossPayment.data).toFixed(2));
} else {
$('#vatAmount').val(vatAmount.amountNull);
$('#grossPayment').val(grossPayment.amountNull);
}
};
So you calculate a number here
vatAmount = (netPayment * VatRate) / 100;
And in here, you treat vatAmount as an object that has a key data
$('#vatAmount').val(parseFloat(vatAmount.data).toFixed(2));
You should just be using the variable. A simple test
console.log("variable itself: ", vatAmount);
console.log("key data: ", vatAmount.data);
So you would need to just do
$('#vatAmount').val(vatAmount.toFixed(2));
$('#grossPayment').val(grossPayment.toFixed(2));
You do the same thing with grossPayment and you reference some other property vatAmount.amountNull
$('#vatAmount').val(vatAmount.amountNull);
$('#grossPayment').val(grossPayment.amountNull);
should be
$('#vatAmount').val(""); //or any error message
$('#grossPayment').val("");