I'm a learning newbie.
In my code at: "https://codepen.io/JonasJsk/pen/qrzLzv"
MYAPPLICATION.DisplayNames = function ()
{
var i, len, str;
for(i = 0, len = MYAPPLICATION.Names.length, str = ""; i < len; ++i)
{
str += MYAPPLICATION.Names[i] + "<br>";
}
console.log(document.getElementById("content").innerHTML = str);
}
I have declared an javascript array with both strings and numbers.
1 - I'm trying to figure out how I can specifically only print-out the strings to the console.
I have been at this for hours, please help me!
答案 0 :(得分:1)
Using your code example you can iterate over MYAPPLICATION.Names
array with the method Array.prototype.forEach() and validate the typeof every element in the array is an string
:
var MYAPPLICATION = MYAPPLICATION || {};
MYAPPLICATION.Names = ["Superman", "Batman", "Flash", 66, 23, 97]
MYAPPLICATION.DisplayNames = function () {
var content = document.getElementById('content');
var ul = document.createElement('ul');
MYAPPLICATION.Names.forEach(function (item) {
if (typeof item === 'string') {
var li = document.createElement('li');
li.appendChild(document.createTextNode(item));
ul.appendChild(li);
}
});
content.innerHTML = '';
content.appendChild(ul);
}
<h2>Lab #2.1</h2>
<button type="button" onclick="MYAPPLICATION.DisplayNames()">
Get Names
</button>
<div id="content"></div>
答案 1 :(得分:0)
You can use the typeof operator like this :
var aList = [1, 2, 3, "one", "two", "three"];
for(var i = 0; i < aList.length; i++) {
if(typeof(aList[i]) == "string")
console.log("This is a string : "+aList[i]);
}
I hope this helps. :)
答案 2 :(得分:0)
I don't understand your question... Do you want to remove the numbers from the array or you want to print the information only on the console.log
?
Anyway, try this one:
var MYAPPLICATION = MYAPPLICATION || {};
MYAPPLICATION.Names = ["Superman", "Batman", "Flash", 66, 23, 97]
MYAPPLICATION.DisplayNames = function ()
{
//MYAPPLICATION.myJSON = JSON.stringify(MYAPPLICATION.Names);
var i, len, str;
for(i = 0, len = MYAPPLICATION.Names.length, str = ""; i < len; ++i)
{
if (!isNaN(MYAPPLICATION.Names[i])) { continue; }
str += MYAPPLICATION.Names[i] + "<br>";
}
console.log(document.getElementById("content").innerHTML = str);
}
You can also remove the console.log
if you don't want to print in the console.
Like:
var MYAPPLICATION = MYAPPLICATION || {};
MYAPPLICATION.Names = ["Superman", "Batman", "Flash", 66, 23, 97]
MYAPPLICATION.DisplayNames = function ()
{
var i, len, str;
for(i = 0, len = MYAPPLICATION.Names.length, str = ""; i < len; ++i)
{
name = MYAPPLICATION.Names[i]
if (!isNaN(name)) { continue; }
str += name + "<br>";
}
document.getElementById("content").innerHTML = str;
}
答案 3 :(得分:0)
//considering that the key is added when you have at least one incident
if (yourHash.get("yourDateStringWhatEverTheFormatIs") != null)