Javascript concatenate strings in array - javascript

Why does the following code not work? Can't figure it out.
var string = "";
for (var x; x < numbersArray.length; x++)
string += numbersArray[x];
alert(string);
string is empty at the end.

x is undefined, which is not less than any number.
Therefore, your terminating condition is always false.
You probably want to start at 0.

var string = "";
for (var x=0; x < numbersArray.length; x++)
string += numbersArray[x];
console.log(string);
Just make sure to initialize your x.

Related

Any alternative way of using this .charAt()?

I have a problem, when I used input[index] in the statement the reverse word didn't match the value of inputString. But this works in C#. When I try it in JavaScript is not working. I want to learn what are the other alternative way of .char() method. Can anybody solve my problem?
strReverse = "";
input = document.getElementById("inputValue").value;
i = input.length;
for(var j = i; j >= 0; j--) {
strReverse = strReverse + input.charAt(j); // i used input[index]
}
If you wish to use input[index] instead of input.charAt() then you need to address the issue that you are setting i = input.length;
So when you enter your loop for the first iteration, j will be equal to i. Meaning that you are trying to access the character at the index equal to the length of the string (when you do input[j]). However, as arrays and string indexing starts at zero in javascript (and in most languages), there is no index at i (the length of the string), but, there is an index at i-1, which will give the last character in the string. Thus, if you want to reverse your array using input[j] you need to start j in your for loop as j = i - 1.
Take a look at the snippet for a working example:
strReverse = "";
input = "level";
i = input.length;
for(var j = i-1; j >= 0; j--) {
strReverse = strReverse + input[j]; // i used input[index]
}
if(strReverse === input) {
alert(input +" is a palindrome!")
} else {
alert(input +" is not a palindrome!");
}

NaN appearing because of quotes within split property

I'm sorry if this has already been answered here, but I'm not entirely sure what to even look for. I've recently started learning to code as something I've seen as enjoyable. I used a website and it told me that I had learned all I needed to about javascript (though I don't think that's true). To get some practice and a better handle on it I decided to do some challenges. I was working on one and got it mostly right. It said to reverse any input string (I was not required to code how to input, at least I think). The input is str. I've gotten it to reverse all of the characters, including punctuation, except quotations. To input, the phrase is required to be in quotations. In my result, instead of having quotations, it has a NaN before the phrase.
Here is the code I made
function FirstReverse(str) {
var strL = str.length;
var strS = str.split("");
for(var i = 0; i <= str.length; i++){
var strC = strC + strS[strL];
strL = strL -1;
}
// code goes here
return strC;
}
// keep this function call here
FirstReverse(readline());
and if I input "Hello, world", I get NaNdlrow ,olleH. I'm new, so it would help if this can be put into simpler terms. what you see in the code is about the most advanced stuff I know.
Thank you for your time.
The reason you're getting NaN is because you never initialized strC, and you're also accessing outside the strS array.
You should initialize strC to an empty string.
And to prevent accessing outside the array, initialize strL to str.length-1, since array indexes go from 0 to length-1.
And the loop should repeat when i < str.length, not i <= str.length, otherwise you'll go past the beginning as well.
function FirstReverse(str) {
var strL = str.length-1;
var strS = str.split("");
var strC = "";
for(var i = 0; i < str.length; i++){
strC = strC + strS[strL];
strL--;
}
// code goes here
return strC;
}
// keep this function call here
console.log(FirstReverse("abcdef"));
You need to switch around your for loop and define strC to be blank. Since strC is undefined the first time you run strC = strC + strS[i]; is causing the NaN problem. Also, it seems easier to start at str.length and decrement to 0. Lastly, as previously posted there's no need for the call to split.
function FirstReverse(str) {
var strL = str.length-1;
var strC = "";
for(var i = strL; i >= 0; i--){
strC = strC + str[i];
}
// code goes here
return strC;
}
function FirstReverse(str)
{
var strC = "";
var strS = str.split("");
for(var i = str.length-1; i >= 0 ; i--) {
strC += strS[i];
}
return strC;
}
FirstReverse("hello, world");
You have two simple errors in your code that are leading you to that "NaN" at the beginning of your string.
1) You need to declare your strC variable outside of the loop so that it has an initial value of empty string, var strC = "";. Currently the first time through your loop it is undefined.
2) The second mistake is that the variable you are using for indexing the values, strL, starts off as the length of the input string, when it should be one less. This is because the array is zero-indexed so the last item in the array is at strS[strS.length - 1]. (strS.length and str.length in your code are the same)
For example: The string "abc" has a length of 3 and so strS would be equal to ["a", "b", "c"] (also with a length of 3) and so strS[0] is equal to "a" and strS[2] is equal to "c". But since you are starting from the length itself instead of length - 1, on the first iteration of the loop you are asking for strS[3] which is undefined.
So for this issue, subtract one from the length when you initialize the variable: var strL = str.length - 1;
The reason this is resulting in the letters "NaN" is because in JavaScript NaN is a special value that means "Not a Number" and is represented when converted to a string as "NaN".
On your first loop strC is undefined (the first issue) and strS[strL] is undefined (the second issue) so your statement translates to var strC = undefined + undefined;. In JavaScript undefined + undefined is treated as a mathematical expression and results in NaN.
So at the start of the second time through the loop, strC is equal to NaN and strL is now pointing to the last item in the array so you get the "d" from the end of "Hello, world". So your statement translates to strC = NaN + "d";, the NaN is converted to a string since + is treated as the string concatenation operator and you end up with "NaNd" and then the rest of your loop runs through just fine.
There are some better ways of doing what you are trying to accomplish, but as you learn and practice more you'll figure them out and now you know why your code is doing what it is and where this weird "NaN" nonsense is coming from. :)
Also, I think that you seem confused as to why your input has quotes but not the output. You are inputting a string with the content Hello, world but strings are represented in code surrounded by quotes ala "Hello, world" so you shouldn't get quotes in the output.
Oh, and just for clarity, your code corrected looks like this:
function FirstReverse(str) {
var strL = str.length - 1;
var strS = str.split("");
var strC = "";
for (var i = 0; i <= str.length; i++) {
strC = strC + strS[strL];
strL = strL - 1;
}
return strC;
}
But there are simpler ways such as counting down from the input length using the loop counter itself:
function FirstReverse(str) {
var strS = str.split("");
var strC = "";
for (var i = str.length - 1; i >= 0; i--) {
strC = strC + strS[i];
}
return strC;
}
And even accessing the string itself without bother with split:
function FirstReverse(str) {
var strC = "";
for (var i = str.length - 1; i >= 0; i--) {
strC = strC + str[i];
}
return strC;
}
Or even just using some built-in string and array functions:
function FirstReverse(str) {
return str.split("").reverse().join("");
}
I think I managed to find the mistake. Change the for cycle from
for(var i = 0; i <= str.length; i++) to for(var i = 0; i < str.length; i++). Let me know what happened after the changes were done!

javascript string algorithm

Let's say I have a string variable called myString, and another string variable called myChar.
var myString = "batuhan"; // it's user input.
var myChar = "0"; // will be one character, always
What I need is, a function that returns all the combinations of myString and myChar.
Like:
"batuhan","batuha0n","batuh0an","batuh0a0n","batu0han","batu0ha0n","batu0h0an","batu0h0a0n","bat0uhan","bat0uha0n","bat0uh0an","bat0uh0a0n","bat0u0han","bat0u0ha0n","bat0u0h0an","bat0u0h0a0n","ba0tuhan","ba0tuha0n","ba0tuh0an","ba0tuh0a0n","ba0tu0han","ba0tu0ha0n","ba0tu0h0an","ba0tu0h0a0n","ba0t0uhan","ba0t0uha0n","ba0t0uh0an","ba0t0uh0a0n","ba0t0u0han","ba0t0u0ha0n","ba0t0u0h0an","ba0t0u0h0a0n","b0atuhan","b0atuha0n","b0atuh0an","b0atuh0a0n","b0atu0han","b0atu0ha0n","b0atu0h0an","b0atu0h0a0n","b0at0uhan","b0at0uha0n","b0at0uh0an","b0at0uh0a0n","b0at0u0han","b0at0u0ha0n","b0at0u0h0an","b0at0u0h0a0n","b0a0tuhan","b0a0tuha0n","b0a0tuh0an","b0a0tuh0a0n","b0a0tu0han","b0a0tu0ha0n","b0a0tu0h0an","b0a0tu0h0a0n","b0a0t0uhan","b0a0t0uha0n","b0a0t0uh0an","b0a0t0uh0a0n","b0a0t0u0han","b0a0t0u0ha0n","b0a0t0u0h0an","b0a0t0u0h0a0n"
Rules: myChar shouldn't follow myChar
How can I do that? Really my brain dead right now :/
It's possible to implement what you want using recursion.
// Example: allCombinations("abcd", "0") returns the array
// ["abcd", "abc0d", "ab0cd", "ab0c0d", "a0bcd", "a0bc0d", "a0b0cd", "a0b0c0d"]
function allCombinations(str, chr) {
if (str.length == 1)
return [str];
var arr = allCombinations(str.substring(1), chr);
var result = [];
var c = str.charAt(0);
for (var i = 0; i < arr.length; i++)
result.push(c + arr[i]);
for (var i = 0; i < arr.length; i++)
result.push(c + chr + arr[i]);
return result;
}
You may or may not have noticed this but this is basically counting in binary. If we define bit 0 to be the absence of myChar and bit 1 to be the presence of myChar, then the following sequence:
var myString = ".....";
var myChar = "1";
var sequence = [
".....1",
"....1.",
"....1.1",
"...1.."
];
is basically counting from 1 to 4 in binary:
var sequence = [
0b0000001,
0b0000010,
0b0000011,
0b0000100
];
Therefore, all you need is a for loop to count up to the bit amount of the length of the string plus 1 (because the position at the end of the string is also legal):
var len = Math.pow(2,myString.length+1);
for (var x = 0; x < len; x++) {
// x in binary is all the possible combinations
// now use the "1" bits in x to modify the string:
// Convert myString to array for easy processing:
var arr = myString.split('');
arr.push(""); // last position;
for (var i = myString.length; i >= 0; i--) {
if ((x >> i) & 0x01) { // check if bit at position i is 1
arr[i] = myChar + arr[i];
}
}
console.log(arr.join('')); // print out one combination
}
Of course, this works only for small strings of up to 31 characters. For larger strings you'd need to do the binary counting using things other than numbers. Doing it in a string form is one option. Another option is to use a bigint library such as BigInteger.js to do the counting.

JavaScript Array- adding the values together

I'm trying to take numbers inputted by a user. Store those number inside an array and then add up all values inside the array to get a total number. I'm using numbers 1 -7 to test.
I print the output of the array and I get:
1,2,3,4,5,6,7
returned so it seems that storing the data in an array is working. However when I try to add the values inside the array I get:
01234567
Which makes it look like the function is just pushing the numbers together. I feel like I'm missing something really obvious here but I can't figure out what it is. Any help would be appreciated.
var again = "no";
var SIZE = 7;
var pints = [];
var totalPints = 0;
var averagePints = 0;
var highPints = 0;
var lowPints = 0;
getPints(pints[SIZE]);
getTotal(pints[SIZE]);
println(pints);
println(totalPints);
function getPints()
{
counter = 0;
while (counter < 7)
{
pints[counter] = prompt("Enter the number of pints");
counter = counter + 1;
}
}
function getTotal()
{
counter = 0;
totalPints = 0
for (var counter = 0; counter < 7; counter++)
{
totalPints += pints[counter]
}
}
You can use parseInt to convert the pints values like this
totalPints += parseInt(pints[counter], 10);
And you don't have to hardcode the length like this
for (var counter = 0; counter < 7; counter++)
instead you can use pints.length like this
for (var counter = 0; counter < pints.length; counter++)
Your array contains the strings instead of their integer values, instead of
totalPints += pints[counter];
Try using something like this -
totalPints += parseInt(pints[counter], 10);
That happens since each number is read as a string, not a number. Change:
pints[counter] = prompt("Enter the number of pints");
to:
pints[counter] = +prompt("Enter the number of pints");
to convert the value to a Number so that you get addition instead of concatenation from the + operator.
["1", "2", "3", "4", "5", "6", "7"]
01234567
This is the output produced by your code. Note that values in the array are in quotes, so that means their type is String. When using + with strings you get string concatenation.
That's why you have to convert them to a number.
There are multiple ways to do so.
-> parseInt("5")
-> 5
-> "5" * 1
-> 5
-> Number("5")
-> 5
Change
totalPints += pints[counter]
to
totalPints += parseInt(pints[counter])
parseInt will convert the string values to integers.

how to add array element values with javascript?

I am NOT talking about adding elements together, but their values to another separate variable.
Like this:
var TOTAL = 0;
for (i=0; i<10; i++){
TOTAL += myArray[i]
}
With this code, TOTAL doesn't add mathematically element values together, but it adds them next to eachother, so if myArr[1] = 10 and myArr[2] = 10 then TOTAL will be 1010 instead of 20.
How should I write what I want ?
Thanks
Sounds like your array elements are Strings, try to convert them to Number when adding:
var total = 0;
for (var i=0; i<10; i++){
total += +myArray[i];
}
Note that I use the unary plus operator (+myArray[i]), this is one common way to make sure you are adding up numbers, not concatenating strings.
A quick way is to use the unary plus operator to make them numeric:
var TOTAL = 0;
for (var i = 0; i < 10; i++)
{
TOTAL += +myArray[i];
}
const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });
Make sure your array contains numbers and not string values. You can convert strings to numbers using parseInt(number, base)
var total = 0;
for(i=0; i<myArray.length; i++){
var number = parseInt(myArray[i], 10);
total += number;
}
Use parseInt or parseFloat (for floating point)
var total = 0;
for (i=0; i<10; i++)
total+=parseInt(myArray[i]);

Categories

Resources