Jump to content

Changing an output from console to the browser (i.e document)


DocGrimwig

Recommended Posts

I am new to js and am trying to learn something via the following snippet:

 

<code>
function substrings(str1)
{
var array1 = [];
for (var x = 0, y=1; x < str1.length; x++,y++)
{
array1[x]=str1.substring(x, y);
}
var combi = [];
var temp= "";
var slent = Math.pow(2, array1.length);
for (var i = 0; i < slent ; i++)
{
temp= "";
for (var j=0;j<array1.length;j++) {
if ((i & Math.pow(2,j))){
temp += array1[j];
}
}
if (temp !== "")
{
combi.push(temp);
}
}
document.write.log(combi.join("n"));
}
substrings("dog");
</code>
(1) how can I change the output to go to my browser instead of the console and
(2) can someone please answer a stupid question like what is the benefit of writing to the console. As I said I am totally new and don't have handle on the uses of the console yet. I know its for debugging, i think... :-)
Link to comment
Share on other sites

To write to the console it's console.log(), not document.write.log(). Writing to the console is used to look at the values that your application is using. In order to make use of your function you need to change document.write.log(combi.join("n")); to return combi;

 

To put the results of your function onto the page you need to access an element through the HTML DOM and change its innerHTML property or add new elements to the page using createElement() and appendChild().

 

You also can break a string into letters just by using the split() method, like this: var array1 = str1.split("");

 

Here's your code rewritten.

Assume we have this element on the page:

<ul id="data"></ul>

Here's some Javascript code to put the data onto the page:

function substrings(str1) {  var array1 = str1.split("");  var combi = [];  var temp= "";  var slent = Math.pow(2, array1.length);  for (var i = 0; i < slent ; i++) {    temp = "";    for (var j=0;j<array1.length;j++) {      if ((i & Math.pow(2,j))) {        temp += array1[j];      }    }    if (temp !== "") {      combi.push(temp);    }  }  return combi;}// Put the data onto the pagevar element = document.getElementById("data");var data = substrings("dog");var item;for(vat i = 0; i < data.length; i++) {  item = document.createElement("li");  item.innerHTML = data[i];  element.appendChild(item);}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...