Array not showing length - javascript

Been trying for about an hour now, can't get my array to show its length upon a button press. It did show its length at one attempt, but it was a totally different amount to the amount of elements in the array. I read somewhere that it happens that way sometimes, and has something to do with undefined elements. But now it isn't showing any alerts at all.
var fruits("Banana", "Apple", "Orange")
function myFunction() {
alert(fruits.length)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<body>
<script>
src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" >
</script>
<script src="Arrays.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
</head>
<button id="lengthbutton" onclick="myFunction()"> Click me to find out length </button>
</body>
</html>

If you want to declare an array using () you need to use new Array():
var fruits = new Array("Banana", "Apple", "Orange")
function myFunction() {
alert(fruits.length)
}
<button id="lengthbutton" onclick="myFunction()"> Click me to find out length </button>

var fruits = new Array("Banana","Apple", "Orange" );
var fruitsArr = ["Banana","Apple", "Orange" ];
function myFunction(arr) {
console.log(arr.length)
}
myFunction(fruits)
myFunction(fruitsArr)
You can create an array using array literal i.e [] or you can use new Array() to create an array.

Your array declaration is JavaScript code is incorrect. It should be like.
var fruits = ["Banana","Apple","Orange"]
var fruits = ["Banana", "Apple", "Orange"];
function myFunction() {
alert(fruits.length)
}
<button id="lengthbutton" onclick="myFunction()">Find Length of Array</button>

The array literal syntax in JavaScript uses square brackets:
var fruits = [ "Banana","Apple", "Orange" ]

var fruits = ["Banana","Apple", "Orange"]
Your code has something wrong.

You need to use () with new Array() or you can use [] if you do not want to declare it explicitly.
e.g.
var fruits = new Array("Banana", "Apple", "Orange")
OR
var fruits = ["Banana", "Apple", "Orange"]
var fruits = ["Banana", "Apple", "Orange"]
function myFunction() {
alert(fruits.length)
}
<button id="lengthbutton" onclick="myFunction()"> Click me to find out length </button>
OR
var fruits = new Array("Banana", "Apple", "Orange")
function myFunction() {
alert(fruits.length)
}
<button id="lengthbutton" onclick="myFunction()"> Click me to find out length </button>

Related

onChange event not being called with change in value in input tag

Unable to figure out why 'onChange' event is not firing with change in the value of . The onChange event fires when I hit enter when the is in focus. I have added the 'change' event to the tag in a seperate JS file.
The basic function of the JS file is to take value from the and compare it with some strings, and output the matching strings.
//name of fruits
let data=["apple","watermelon","orange","strawberry","grape","cherry","mango","nectarine","banana","pomegranate","raspberry","papaya","kiwi","pineapple","lemon","apricot","grapefruit","peach","avocado","passion fruit","plum","lime","blueberry","lychee","fig"]
//------------------------------------//
//Grabbing important elements
let inputField = document.getElementsByTagName("input")[0];
let ul = document.getElementsByTagName("ul")[0];
//bindings
inputField.addEventListener("change",onChangeHandler);
//functions
function onChangeHandler(){
//empty the ul before inserting anything
ul.innerHTML="";
let queryString = inputField.value;
if(queryString==""){
return;
}
for(i=0;i<data.length;i++){
if(data[i].indexOf(queryString)==0){
let li = document.createElement("li");
li.innerText = data[i];
ul.appendChild(li);
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="container">
<div id="search">
<input type="text">
</div>
<ul id="output">
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
Try using input instead of change
inputField.addEventListener("input",onChangeHandler);
the onChange event only fires when the input box loses focus. The onInput event fires when the input is changed.
Your handler is running but your test:
if(data[i].indexOf(queryString)==0)
should be:
if(data[i].indexOf(queryString)==-1)
because indexOf() returns -1 when the item isn't found, not 0.
Now, you've also got your loop and your if test a little backwards. You need to check to see if the array already has the input value and if not, then add that value to the array... then loop over the array and make list items from it.
Also, don't use getElementsByTagName() in general because it returns a "live node list" and definitely don't put an index on the resulting list. Instead, use .querySelector() (as shown below).
//name of fruits
let data = [
"apple",
"watermelon",
"orange",
"strawberry",
"grape",
"cherry",
"mango",
"nectarine",
"banana",
"pomegranate",
"raspberry",
"papaya",
"kiwi",
"pineapple",
"lemon",
"apricot",
"grapefruit",
"peach",
"avocado",
"passion fruit",
"plum",
"lime",
"blueberry",
"lychee",
"fig"
]
//------------------------------------//
//Grabbing important elements
let inputField = document.querySelector("input");
let ul = document.querySelector("ul");
//bindings
inputField.addEventListener("change", onChangeHandler);
//functions
function onChangeHandler(){
//empty the ul before inserting anything
ul.innerHTML="";
let queryString = inputField.value;
if(queryString==""){
return;
}
// First check to see if the input value is in the array:
if(data.indexOf(queryString)==-1){
// It isn't, so add it to the array
data.push(queryString);
// Then loop over the array
for(i=0;i<data.length;i++){
let li = document.createElement("li");
li.innerText = data[i];
ul.appendChild(li);
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="container">
<div id="search">
<input type="text">
</div>
<ul id="output">
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
inputField.addEventListener("input",onChangeHandler);
Use input event instead of change event, Change event triggers when the element goes out of focus. The input event fires synchronously on change of the content for the element.

How can I put middle dot character inside .join()?

How can I put middle dot character inside .join() for split arrays?
I should put this
<span>·</span>
inside
{product.user.map(ul => ul.names).join(" ")}
If I get the questions correctly, you just need to use dot instead of empty quotation marks.
A Sample modified from w3schools.
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = document.getElementById("demo");
x.innerHTML = fruits.join('.');
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to join the array elements into a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
Yes you can, this should work:
<h1>{product.user.map(ul => ul.names).join(' <span>·</span> ')} </h1>

Declaring Javascript array within a function

Declaring an array within a function triggered by button causes the function to fail and not work as intended. What is the reason this happens? The "function C" block is having the problem.
I have also noticed that the ES6 syntax of "export ..." causes the entire thing to jam as well, it only accepts "module.export".
I am a total beginner, so I have no idea of what is going on.
This is my code:
<!-- Bootstrap CSS -->
<link href="resources/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="resources/custom2.css">
<link href="resources/TCJA's CSS.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
let TA = [0, 0, 0, 0]
function MF() {
TA = [0, document.getElementById("test1").value, document.getElementById("test2").value, document.getElementById("test3").value]
document.getElementById("shout1").innerHTML = TA[1]
document.getElementById("shout2").innerHTML = TA[2]
document.getElementById("shout3").innerHTML = document.getElementById("testCheck").checked
}
function C() {
var ACArray[0] = 2; //AttackerCard Array
var DCArray[0] = 1; //DefenderCard Array
var para = document.createElement("p");
var node = document.createTextNode("The attackers dealt " + document.getElementById("wand").value + " damage to the defenders.");
para.appendChild(node);
var element = document.getElementById("newElement");
element.appendChild(para);
}
</script>
</head>
<body>
<!-- Put code below -->
<br>
<label class="control-label">Tester Input</label>
<input class="form" id="test1">
<input class="form" id="test2">
<input class="form" id="test3">
<br>
<button id="doge" class="btn btn-primary" onclick="MF()"><h3>Result</h3></button>
<br>
<input id="testCheck" type="checkbox"> Check it?
<br>
<h2>Result:</h2>
<p id="shout1">Hello?</p>
<p id="shout2">Hello again?</p>
<p id="shout3">Hello a third time?</p>
<br>
<label class="control-label">Creator Input</label>
<input class="form" id="wand">
<button id="god" class="btn btn-success" onclick="C()"><h3>Create</h3></button>
<br>
<div id=newElement>
</div>
<button id="show">Show</button>
<!-- JQuery -->
<!-- End of body -->
</body>
</html>
What do you mean, by declaring var ACArray[0]=2;? Yes, it looks like declaring new array with first element equals 2, but, where is your array declaration?
The right way to do this: var ACArray = [2]; var DCArray = [1]; and so on.
Declare arrays Before assigning values into an array.
var ACArray = [];
var DCArray = [];
function C(){
ACArray[0] = 2;
DCArray[0] = 1;
}
The following syntax is incorrect:
var ACArray[0]=2; //AttackerCard Array
var DCArray[0]=1; //DefenderCard Array
The most convenient way to declare an array in JS is an Array literal like this:
var array = ['item1', 'item2'];
What we now have done is multiple steps in one. First we have created memory for an array using the var keyword and the array literal syntax.
Step 1:
var array = [];
Then we have initialized the array and put actual values inside the array like this:
Step 2
array[0] = 'item1';
array[1] = 'item2';
Important to understand is that you now can refer to all these elements in the following way:
console.log(array[0]); // logs item1
console.log(array[1]); // logs item2
And also be aware that the counting of the elements in the array starts with 0, not 1.

Adding object to my array of objects using javascript functions

So i have a array of objects, I want to add new object into it. so I am using following code here is my code. I have seen other questions asked on the same topic but still I am not able to add my new object that i am fetching using jquery into my list. I am doing silly mistake please find it for me. Thanks
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<input placeholder="name" type="text" id="name"></br>
<input placeholder="rno" type="text" id="rollno"></br>
<input type="submit" value="Add Roll" id="add" >
<script type="text/javascript">
$(document).ready(function(){
console.log("loaded");
var list=[
{name:"sud",rno:1},
{name:"diya",rno:2},
{name:"sakshi",rno:3}
];
for(i=0;i<list.length;i++){
console.log("old list is"+list[i].rno+"\t"+
list[i].name);
};
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
//here i want to add rno and name to my list
for(i=0;i<list.length;i++){
console.log("new list is"+list[i].rno+"\t"+
list[i].name);
};
});
});
</script>
</body>
</html>
Array#push adds items to the end of an array. eg: arr.push("test");
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
// Use Array#push to add an item to an array.
// No need to use `new` when using the `{}` syntax for object creation.
list.push({name:"sudarshan",rno:"33"});
// Just a tip. You should use `var i = 0;` instead of `i = 0;` to keep the `i` variable out of the global scope.
for(var i = 0; i < list.length; i++){
console.log("new list is"+list[i].rno+"\t"+list[i].name);
};
});
to append to an array you can use push
list.push({name:"sudarshan",rno:"33"});
or just
list[list.length] = {name:"sudarshan",rno:"33"};
which is the same as above.

Comparing two functions in JavaScript

I'm developing a mobile app for my wife's 1st grade class so they can practice sight words. I'm a novice to JavaScript but I was able to pull off my first objective which was to take a JavaScript array and extract a random word from it. My second objective is to have the user type in the word that they see, click a button and have the word they entered be compared to the random word. I attempted to do this with a second function but it did not do it. I don't get any errors in the console so I'm a bit lost on how to get this working. Any help would be greatly appreciated by me and a great group of 1st graders. Here is the code that I have so far.
<!DOCTYPE html>
<html>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>
<input id="yourTurn">
<button onclick="myFunction()">New Word</button>
<button onclick="checkSpelling()">Check My Spelling</button>
<p id="result"></p>
<script>
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var yourTurn = document.getElementById("yourTurn").value;
var aWord = document.getElementById("aWord").value;
var checkWord = (yourTurn == aWord)?"Nice Job!":"So close! Try again!";
function myFunction() {
var showWord = sightWord[Math.floor((Math.random()*10)+1)];
aWord.innerHTML = showWord;
}
function checkSpelling(result) {
document.getElementById("result").innerHTML=checkWord;
}
</script>
</body>
</html>
You mixed up value and innerHTML.
value is used for input and textarea elements and innerHTML is for almost other element
This code will work for you:
<!DOCTYPE html>
<html>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>
<input id="yourTurn">
<button onclick="myFunction()">New Word</button>
<button onclick="checkSpelling()">Check My Spelling</button>
<p id="result"></p>
<script>
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var yourTurn = document.getElementById("yourTurn");
var aWord = document.getElementById("aWord");
function myFunction() {
var showWord = sightWord[Math.floor((Math.random()*10)+1)];
aWord.innerHTML = showWord;
}
function checkSpelling(result) {
var checkWord = (yourTurn.value == aWord.innerHTML)?"Nice Job!":"So close! Try again!";
document.getElementById("result").innerHTML=checkWord;
}
</script>
</body>
</html>
See live code here: http://jsbin.com/ubofus/1/edit
The problem is that you're evaluating checkWord only once, when the browser runs your JavaScript.
So, the checkWord variable is always "Nice Job!".
Another problem is that you're using value on a p element. p elements don't have such properties.
And the last issue is that you're comparing 2 values with ==. It isn't enough, because "" == undefined, undefined being what value on a p element returns.
To sum it up, you want to evaluate checkWord every time, and you want to compare apples to apples. Which would lead to this kind of code:
function checkSpelling(result) {
var yourTurn = document.getElementById("yourTurn").value;
var aWord = document.getElementById("aWord").innerHTML;
var checkWord = (yourTurn == aWord)?"Nice Job!":"So close! Try again!";
document.getElementById("result").innerHTML=checkWord;
}
One last thing: I'm using innerHTML there, but it's bad. You don't want HTML, you want text. It'd be better to use textContent, or innerText on older IE (6, 7, 8). If you don't want to worry about this kind of cross-browser mess, use a library to abstract away all of this.
Okay I got it working for you. I have it in a JS Fiddle: http://jsfiddle.net/D6ERg/4/
<!DOCTYPE html>
<html>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>
<input id="yourTurn">
<button onclick="window.wordApp.newWord()">New Word</button>
<button onclick="window.wordApp.checkSpelling()">Check My Spelling</button>
<p id="result"></p>
<script>
window.wordApp = (function() {
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var aWord = document.getElementById("aWord");
return {
newWord : function() {
var showWord = sightWord[Math.floor((Math.random()*10)+1)];
aWord.innerText = showWord;
},
checkSpelling : function() {
var yourTurn = document.getElementById("yourTurn").value;
var checkWord = (yourTurn == aWord.innerText)?"Nice Job!":"So close! Try again!";
document.getElementById("result").innerHTML=checkWord;
}
}
})();
</script>
</body>
</html>
You had a lot of problems. Things that update need to be in functions. I also removed the global variables for best practices and easier debugging.
The (function() {})(); design pattern may be too advanced for you now, but you can look up closures or watch the video Paul Irish talking about how jQuery works. You will learn a lot. Also the book Javascript The Good Parts by Crockford is a book that I wish I read when I started.
Cleaned up your code a little, also fiddled: http://jsfiddle.net/3Ptzu/
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var yourTurn = document.getElementById("yourTurn").value;
var aWord = document.getElementById("aWord").value;
function myFunction() {
var showWord = sightWord[Math.floor((Math.random()*10)+1)];
document.getElementById("aWord").innerHTML = showWord;
}
function checkSpelling(result) {
var challengeWord = document.getElementById("aWord").innerHTML;
var checkWord = document.getElementById("yourTurn").value;
var result = (challengeWord == checkWord) ? "Nice Job!":"So close! Try again!";
document.getElementById("result").innerHTML = result;
}
This one avoids inline scripts:
HTML
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>
<input id="yourWord">
<button id="newWord">New Word</button>
<button id="spellCheck">Check My Spelling</button>
<p id="result"></p>
JS
//list of words
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
//variable containing the current word
var currentWord;
//reference to the "congrats" box
var result = document.getElementById('result');
//reference to the input
var yourWord = document.getElementById('yourWord');
//when new word is clicked
document.getElementById('newWord').onclick = function () {
//get a new word from the list
aWord.innerHTML = currentWord = sightWord[Math.floor((Math.random() * 10) + 1)];
}
//when spell check is clicked
document.getElementById('spellCheck').onclick = function () {
//compare and announce accordingly
var check = (yourWord.value === currentWord) ? "Nice Job!" : "So close! Try again!";
result.innerHTML = check;
}
There is a difference between innerHTML and value; the value is actually an attribute of the input tag. Here is a cross browser way to handle this, without any inline JavaScript:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>Practice Spelling Test</title>
<meta charset="UTF-8" />
<script>
(function(d){
var modern = (d.addEventListener) ? true : false, load = function(fn){
if(modern) {
d.addEventListener("DOMContentLoaded", fn, false);
} else {
d.attachEvent("onreadystatechange", function(){
if(d.readyState === "complete") {
fn();
}
});
}
}, event = function(obj, evt, fn){
if(modern) {
obj.addEventListener(evt, fn, false);
} else {
obj.attachEvent("on" + evt, fn);
}
}, init = function(){
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"], newWordButton = d.getElementById("newWord"), checkSpellButton = d.getElementById("checkSpell"), aWord = d.getElementById("aWord"), yourTurn = d.getElementById("yourTurn"), result = d.getElementById("result"), lastWord = null, newWord = function(){
var count = Math.floor(Math.random()*(sightWord.length - 1));
if(count == lastWord) {
newWord();
} else {
aWord.innerHTML = sightWord[count];
lastWord = count;
}
}, checkSpell = function(){
var curr = aWord.innerHTML, input = yourTurn.value;
if(curr && input) {
result.innerHTML = (curr == input) ? "Nice Job!" : "So close! Try again!";
}
};
event(newWordButton, "click", newWord);
event(checkSpellButton, "click", checkSpell);
};
load(init);
})(document);
</script>
</head>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"> </p>
<input id="yourTurn" type="text" />
<button id="newWord">New Word</button>
<button id="checkSpell">Check My Spelling</button>
<p id="result"></p>
</body>
</html>

Categories