I am trying to make a function that provides the lowest multiplier of two integers. I've got some embedded JavaScript in my HTML file. It seems like the script isn't even running. It must be a problem with the function right? Because even when I did a simple direct return a*b function and it still didn't run. I am missing something here and can't find it.
<!-- language: lang-js -->
<!DOCTYPE html>
<html>
<body>
<p>The lowest multiple:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
var aArray = [];
var bArray = [];
for(var i = 2; true ; i++){
aArray.push(i*a);
bArray.push(i*b);
if(i%10 == 0){
for each(var item in aArray){
if(bArray.indexOf(item) >= 0){
return item;
}
}
if(i === 100){break;}
}
}
}
var a = prompt("");
var b = prompt("");
document.getElementById("demo").innerHTML = myFunction(a, b);
</script>
</body>
</html>
<!-- language: lang-js -->
<!DOCTYPE html>
<html>
<body>
<p>The lowest multiple:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
var aArray = [];
var bArray = [];
for(var i = 2; true ; i++){
aArray.push(i*a);
bArray.push(i*b);
if(i%10 == 0){
for(var item in aArray){
if(bArray.indexOf(aArray[item]) >= 0){
return aArray[item];
}
}
if(i === 100){break;}
}
}
}
var a = prompt("");
var b = prompt("");
document.getElementById("demo").innerHTML = myFunction(a, b);
</script>
</body>
</html>
for each(var item in aArray)
is not syntactically valid JavaScript. Array.prototype.forEach is a function you could use for iteration.
Related
I'm trying to display four images randomly with a related link, by avoiding to display duplicated images each time. I've found how to randomly display a random image with the link, but I have no idea how to create the loop part and how to check for duplicates. I would appreciate your help.
<script>
function random_imglink(){
var myimages=new Array()
myimages[1]="image1.gif"
myimages[2]="image2.gif"
myimages[3]="image3.gif"
myimages[4]="image4.gif"
myimages[5]="image5.gif"
myimages[6]="image6.gif"
var imagelinks=new Array()
imagelinks[1]="http://www.page1.com"
imagelinks[2]="http://www.page2.com"
imagelinks[3]="http://www.page3.com"
imagelinks[4]="http://www.page4.com"
imagelinks[5]="http://www.page5.com"
imagelinks[6]="http://www.page6.com"
var ry=Math.floor(Math.random()*myimages.length);
if (ry==0)
ry=1;
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>');
}
random_imglink()
</script>
Thanks in advance :)
As stated on this answer, you can create a method for checking of duplicates.
method:
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
usage:
var imagelinks= [0,1,2],
index = contains.call(imagelinks, imagelinks[ry]); //boolean
Outside of your function, declare an array to hold elements that are already displayed:
var displayed = [];
Then after your if (ry==0) condition add this:
if (displayed.indexOf(ry) !== -1){
displayed.push(ry);
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>');
} else {
random_imglink();
}
You should learn about Constructors. When you call new on them they return an Object which has separate properties based on the Constructor. Below is some code that will help you along your journey.
//<![CDATA[
// external.js
var doc, bod, htm, C, E, inArray, ShuffleMagic; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
inArray = function(needle, haystack){
for(var i=0,l=haystack.length; i<l; i++){
if(haystack[i] === needle){
return true;
}
}
return false;
}
function ShuffleMagic(haystack){
var a;
this.haystack = haystack;
this.alterOriginal = false;
this.shuffle = function(limit){
var r, s = this.haystack;
if(!a){
a = [].slice.call(s), l = a.length;
for(var i=0,n=1,f,h; i<l; i++,n++){
f = Math.floor(Math.random()*n); h = a[i]; a[i] = a[f]; a[f] = h;
}
}
if(limit){
if(a.length >= limit){
r = a.splice(0, limit);
if(a.length < limit)a = undefined;
}
else{
a = undefined;
return this.shuffle(s.length);
}
}
else{
r = a; a = undefined;
}
if(this.alterOriginal){
s.splice.apply(s, [0, s.length].concat(r)); a = undefined;
}
return r;
}
}
var imagelinks = ['http://www.page1.com', 'http://www.page2.com', 'http://www.page3.com', 'http://www.page4.com', 'http://www.page5.com', 'http://www.page6.com', 'http://www.page7.com', 'http://www.page8.com', 'http://www.page9.com',
'http://www.page10.com', 'http://www.page11.com', 'http://www.page12.com', 'http://www.page13.com', 'http://www.page14.com', 'http://www.page15.com', 'http://www.page16.com', 'http://www.page17.com', 'http://www.page18.com', 'http://www.page19.com'];
var max = E('limit'), out = E('out');
var wow = new ShuffleMagic(imagelinks);
// wow.alterOriginal = true;
// wow.haystack = ['Replace', 'other', 'array, 'example'];
E('testButton').addEventListener('click', function(){
out.innerHTML = wow.shuffle(+max.value).join('<br />');
});
});
//]]>
/* external.css */
html,body{
margin:0; padding:0;
}
.main{
width:980px; margin:0 auto;
}
#limit{
width:30px; padding-left:3px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Shuffle Magic</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='test.js'></script>
</head>
<body>
<div class='main'>
<label for='limit'>Limit:</label><input id='limit' name='limit' type='text' value='4' /><input id='testButton' type='button' value='Click Me' />
<div id='out'></div>
</div>
</body>
</html>
With this version, which is recursive (probably beyond your understanding right now), the array elements only recycle once they've been completely or nearly completely gone through. Enjoy!
Why does the following not produce any result? I get a blank page. I kept modifying/simplifying the code to see where the problem is and it seems to be with the line
"var count = NbnamePattern(names)"
Things seem to work when the body script calls a function defined in the head but with no arguments passed.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 2 Q4</title>
<meta charset="utf-8" />
<script>
function NbnamePattern(var names) {
var count = 0;
for (var i in names) {
if (names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
}
return count;
}
</script>
</head>
<body>
<p></p>
<script type="text/javaScript">
var names = new Array("freddie", "bob", "mieke", "yahoo2", "georgey"); var count = NbnamePattern(names); document.getElementsByTagName("p")[0].innerHTML = "The number of names having these two patterns (/ie$/) and (/y$) in the array is:" + count;
</script>
</body>
</html>
function NbnamePattern(var names){
var count = 0;
for(var i in names)
if(names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
return count;
}
should be
function NbnamePattern(names){
var count = 0;
for(var i in names)
if(names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
return count;
}
The functions in javascript dont take types, it should just be name
you need to remove the var from NbnamePattern(var names) function
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 2 Q4</title>
<meta charset="utf-8" />
<script>
function NbnamePattern(names) {
var count = 0;
for (var i in names) {
if (names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
}
return count;
}
</script>
</head>
<body>
<p></p>
<script type="text/javaScript">
var names = new Array("freddie", "bob", "mieke", "yahoo2", "georgey"); var count = NbnamePattern(names); document.getElementsByTagName("p")[0].innerHTML = "The number of names having these two patterns (/ie$/) and (/y$) in the array is:" + count;
</script>
</body>
</html>
In my code I try to comapare the current element from the array tmp with the types string and number. With this compare I want to print in the console the result different, i.e. if is a string to print it on the same line(the whole word), the next word to be on the second line and so on. But if is a number every digit to print in the new line.
Output number
Input string
Output string
HTML
<!Doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Exercises in JS</title>
<script src="exercises.js"></script>
<body>
<label for="myText">Input array:</label>
<input type="text" id="myText">
Submit
<br/>
<br/>
<label for="myText2">Input for delete:</label>
<input type="text" id="myText2">
Submit
</body>
</head>
</html>
Javascript
window.onload = function(){
inputBox =document.getElementById("myText");
btn = document.getElementById('sub');
inputBox2 = document.getElementById("myText2");
btn2 = document.getElementById('sub2');
btn.addEventListener("click",function(event){
event.preventDefault();
saveArr(inputBox.value);
});
btn2.addEventListener("click",function(event){
event.preventDefault();
removeItemAndprintNewArray(inputBox.value, inputBox2.value);
});
function saveArr(arr) {
var rv = [];
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
function removeItemAndprintNewArray(rv, number) {
var tmp = [],
st = "";
for(var index in rv){
if(rv[index] !== number){
tmp.push(rv[index]);
}
}
for (var i = 0; i < tmp.length; i++){
if (typeof(tmp[i]) == "String"){
st += tmp[i];
console.log(st);
}
else if (typeof(tmp[i]) === "Number"){
st += tmp[i];
console.log(st[i]);
}
}
}
}
Javascript automatically makes type conversations, and if conversation fails it returns NaN value instead of throw exception. Let's use it)
Small example
var arr = [12, "asd", 4];
arr.forEach(function(item) {
console.log(item - 0);
});
So you can check on NaN, don't forget that you should use special function isNaN()
var arr = [12, "asd", 4];
arr.forEach(function(item) {
if(isNaN(item - 0)) {
//do what you want with string
console.log("string");
};
else {
//do what you want with Number
console.log("number");
}
});
I have the base of words like:
var words = [
["english_word1","german_word1"],
["english_word2","german_word2"],
["english_word3","german_word3"]
];
and I need a simple javascript for translating the words in both directions i.e. english -> german and german -> english. Something like:
<textarea id="source" onkeyup="translate();"></textarea>
<div id="result"></div>
<script type="text/javascript">
function translate() {
var source = document.getElementById('source').value;
... ???
document.getElementById('result').innerHTML = result;
}
</script>
Without changing the base
You can try this code
<html>
<head>
<script>
var words = [
["english_word1","german_word1"],
["english_word2","german_word2"],
["english_word3","german_word3"]
];
function getlang(){
var select = document.getElementById("language");
return select.options[select.selectedIndex].value*1;
}
function search(keyword){
for(var x = 0; x < words.length; x++){
var lang = getlang()
if(words[x][lang] == keyword) return words[x][(lang+1) % 2]
}
return false
}
function update(e){
var source = document.getElementById('source').value;
result = search(source);
if(result !== false)
document.getElementById('result').innerHTML = result;
}
document.addEventListener("input",function(e){
if(e.target.id == "source"){
update()
}
});
document.addEventListener("change",function(e){
if(e.target.id == "language"){
update()
}
});
</script>
</head>
<body>
<textarea id = "source"></textarea>
<select id = "language">
<option value = 0>English -> German</option>
<option value = 1>German -> English</option>
</select>
<div id = "result"></div>
</body>
</html>
Hi I want to sort the string based on numbers present in it
e.g
1.1.act2
13.1.2.1.act3
2.1.4.act56
1.3.actorg
3.1.3.args
13.1.3.4.acr
I want to this in a manner
1.1.act2
1.3.actorg
2.1.4.act56
3.1.3.args
13.1.2.1.act3
13.1.3.4.acry
How do I achieve it in javascript?
You can use the Arrays sort method with a custom iterator function. e.g:
mylist = ["1.1.act2", "13.1.2.1.act3", "2.1.4.act56", "1.3.actorg", "3.1.3.args", "13.1.3.4.acr"];
mylist.sort(function(a, b) {
a = a.split("."); b = b.split(".");
var parts = Math.min(a.length, b.length);
for(var i = 0; i < parts; ++i) {
var numA = parseInt(a[i]); var numB = parseInt(b[i]);
if (numA != numB)
return numA > numB;
}
});
This is a stub and untested, but I guess you see where I'm heading
Try this. This code is not optimized but it works
<script type="text/javascript">
function fnc()
{
var arr=new Array();
arr[0]="1.1.act2";
arr[1]="13.1.2.1.act3";
arr[2]="2.1.4.act56";
arr[3]="1.3.actorg";
arr[4]="3.1.3.args";
arr[5]="13.1.3.4.acr";
var it0=arr[0].split(".");
var it1=arr[1].split(".");
var it2=arr[2].split(".");
var it3=arr[3].split(".");
var it4=arr[4].split(".");
var it5=arr[5].split(".");
var newarr=new Array();
newarr[0]=parseInt(it0[0],10);
newarr[1]=parseInt(it1[0],10);
newarr[2]=parseInt(it2[0],10);
newarr[3]=parseInt(it3[0],10);
newarr[4]=parseInt(it4[0],10);
newarr[5]=parseInt(it5[0],10);
newarr.sort(function(a,b){return a-b});
alert(newarr);
for(i=0;i<arr.length;i++)
{
if(newarr[i]==it0[0])
{console.log(arr[0]);}
else if(newarr[i]==it1[0])
{console.log(arr[1]);}
else if(newarr[i]==it2[0])
{console.log(arr[2]);}
else if(newarr[i]==it3[0])
{console.log(arr[3]);}
else if(newarr[i]==it4[0])
{console.log(arr[4]);}
else if(newarr[i]==it5[0])
{console.log(arr[5]);}
else if(newarr[i]==it6[0])
{console.log(arr[6]);}
}
}
<input type="button" onclick="fnc()" value="click" />