I have this piece of code in javascript:
var i = 0;
var j = 0;
while (allTextLines.length) {
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
if (i == 0) {
alert(temp);
i++;
}
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
var y = line[3];
var z = line[5];
var g = line[7];
lines[j] = (x + ", " + z + ", " + g);
j++;
}
And it's happening something really weird. When i==0, it alerts temp and its split. After that I'm getting:
Uncaught TypeError: Cannot read property 'split' of undefined
If I remove the if, I will have this error right on the start. But if I do something like this:
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
alert(temp);
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
It has no problem splitting (also the alert shows that it has been correctly split). The only problem is that I will have to click "ok" 5600 times. I don't understand what the hell is going on and why I am having this error.
I'm splitting a CSV file with lines like this:
35105,201401,503781827,"8400258","Faro","Lagoa (Algarve)","Portugal"
and I'm trying to add an '-' in here: "8400258", so it becomes "8400-258"
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
Won't that fail when allTextLines only has one element in it, since the array is zero-based? I think you'd need to change the line[x] param to 0:
var temp = line[0].split('');
Might I suggest a different approach?
var line = allTextLines.shift().split(',');
var x = line[3].replace(/^"(\d{4})(\d{3})"$/, "$1-$2");
var y = line[4];
var z = line[5];
var g = line[6];
If you can trust that the format of the data is always the same, it's much less complex to do a pattern based replace than splitting a string like an array and re-assembling it.
Related
I am new to javascript, i tried to modify a text shown below with substring command.
eg. "ABCD_X_DD_text" into "ABCD-X(DD)_text" this
i used this
var str = "ABCD_X_DD_cover";
var res = str.substring(0,4)+"-"+str.substring(5,6)+"("+str.substring(7,9)+")"+str.substring(9,15);
// print to console
console.log(res);
i got what i want. But problem is X and DD are numerical (digit) value. and they are changeable. here my code just stop working.
it can be ..... "ABCD_XXX_DDDD_text" or "ABCD_X_DDD_text".
could you suggest some code, which works well in this situation.
You can use a split of the words.
var strArray = [
"ABCD_X_DD_cover",
"ABCD_XX_DD_cover",
"ABCD_XXX_DD_cover"
];
for(var i = 0; i < strArray.length; i++){
var split = strArray[i].split("_");
var str = split[0] + "-" + split[1] + "(" + split[2] + ") " + split[3];
console.log(str);
}
I used a for cycle using an array of strings, but you can do it with a variable too.
I have been trying to use JavaScript array to push my object by header
like this :
var tab_temp = new Y.TabView(
{ srcNode: '#' + tabId }
);
tabsArray['"' + type + "_" + subTypes + '"'] = tab_temp;
Let's type = "x" and subTypes = "y", so I was expecting the object when I write something like:
tabs["x_y"]
But there is problem with this. When I debug, I can see this array will hold an object "x_y" but length of the array is 0
I can't use push also because in that way I need to use index to get it back but it is tough since sequence might change.
Edit 1:
I am using this because I want to hold a couple of TabView objects. Otherwise I can't reach those object after they created. (AlloyUI). I was able to push those object inside of array. As you see "Baru_BARANG" include and object that start with: s
Edit 2:
Thanks for help, I fixed it. I used Object instead of Array for this:
var tabs = {}
tabs[x + "_" + y] = "z";
I get the value by tabs[x + "_" + y]
You really need to be reading more about working with objects in JavaScript.
Try here first.
var type = "x";
var subType = "y";
var tabsArray = {};
tabsArray[type + "_" + subType] = "z";
console.log("tabsArray = ");
console.log(tabsArray);
console.log("tabsArray['x_y'] = " + tabsArray["x_y"]); // output: z
// Including code added to question as a comment:
var tabsArray = [];
var x = "x";
var y = "y";
tabsArray[x + "_" + y] = "z";
console.log("tabsArray['x_y'] = " + tabsArray["x_y"]);
// tabsArray.length will still be 0. To set .length you can use:
for (var i = 0; i < tabsArray.length; i++) {
tabsArray.length = ++i;
};
console.log("tabsArray.length = " + tabsArray.length);
You are most likely instantiating tabsArray as an array, i.e. var tabsArray = [];. This results in the observed behavior.
Since you want to define the keys yourself, you should instantiate it as an object instead:
var tabsArray = {};
tabsArray['x_y'] = 'z';
More about working with objects in JavaScript.
Basically i'm creating a script to display the place value for set of numbers. Here's my script:
var arrn = '3252';
var temp = 0;
var q = arrn.length;
var j = 0;
for (var i = q-1; i >= 0; i--,j++) {
if (j!=0) temp = temp + ' + ';
{
temp += arrn[i] * Math.pow(10, j);
}
}
alert(temp);
My goal is to achieve 3000 + 200 + 50 + 2. But i get 2 + 50 + 200 + 3000. I tried temp.reverse() & sort functions but doesn't seem to work. Please help
Change
if(j!=0)temp=temp +' + ';
{
temp +=arrn[i]*Math.pow(10,j);
}
to
if(j!=0) {
temp=' + ' + temp;
}
temp = arrn[i]*Math.pow(10,j) + temp;
Live Example
Side note: Your braces in the first code block above are very misleading. What you have:
if(j!=0)temp=temp +' + ';
{
temp +=arrn[i]*Math.pow(10,j);
}
is
if(j!=0)temp=temp +' + ';
temp +=arrn[i]*Math.pow(10,j);
which is to say
if(j!=0) {
temp=temp +' + ';
}
temp +=arrn[i]*Math.pow(10,j);
the block in your version is not associated with the if, it's just a freestanding block.
Side note #2: Since you're using temp as a string everywhere else, I would initialize it with '' rather than with 0. Example The reason your string didn't end up with an extraneous 0 was really quite obscure. :-)
Just add the number to the beginning of the string instead of at the end:
for (var i = q - 1; i >= 0; i--, j++) {
if (j != 0) {
temp = ' + ' + temp;
}
temp = arrn[i] * Math.pow(10, j) + temp;
}
Demo: http://jsfiddle.net/Guffa/rh9oso3f/
Side note: You are using some confusing brackets in your code after the if statement. As there is a statement following the if statement, the brackets starting on the next line becomes just a code block, but it's easy to think that it's supposed to be the code that is executed when the condition in the if statement is true.
Another side note: the language attribute for the script tag was deprecated many years ago. Use type="text/javascript" if you want to specify the language.
How about temp.split("+").reverse().join(" + ")?
You can do this way. I know it can be optimised. But it works
var arrn='3252';
var temp=0;
var q=arrn.length;
var res = [];
var j=0;
for(var i=q-1;i>=0;i--,j++)
{
temp += parseFloat(arrn[i])*Math.pow(10,j);
res.push(arrn[i]*Math.pow(10,j));
}
res.reverse();
alert(res.join('+') + " = " + temp);
http://jsfiddle.net/he7p8y5m/
var arrn='3252';
var temp=new Array();
var q=arrn.length;
for(var i=0;i<=q-1; i++){
temp.push(arrn[i]*Math.pow(10,(q-i-1)));
}
temp = temp.join('+');
alert(temp);
I am trying to create a format for a graph. When I try to do so I am getting an undefined with console.log before the data. Here's my code
$(document).ready(function () {
var graphData = new Array();
$.getJSON("ds/js.json", function (Data) {
dataLength = returnedData.data.length;
var x = new Array();
var y = new Array();
var mytext, dataa, f;
for (i = 0; i < dataLength; i++) {
x[i] = Data.data[i].avgPrice;
y[i] = Data.data[i].numProducts;
}
for (var a = 0; a < 6; a++) {
mytext = "x:" + x[a] + "," + "y:" + y[a] + "}" + "," + "{";
dataa = dataa + mytext;
}
console.log(dataa);
var f =
"[{data : [{" + dataa;
console.log(f);
});
drawGraph(graphData);
});
Console output :
undefinedx:87.6,y:85},{x:116.08,y:61},{x:113.11,y:49},{x:181.37,y:65},{x:138.14,y:74},{x:66.03,y:89},x:66.03,y:89},{
What am I doing wrong here? And also I want a separate format for a=5, that stops the ", {" coming at the end.
When you do this:
for (var a=0;a<6;a++){
mytext = "x:" +x[a] + "," + "y:" +y[a] + "}" + "," + "{" ;
dataa=dataa+mytext;
}
you're performing string concatenation with dataa and mytext. However, in the first iteration of that for loop dataa has not yet been initialised, and the string representation of that is undefined.
When you declare the dataa variable initialise it as an empty string instead:
var mytext,dataa = '',f;
As an aside, it's important to remember that $.getJSON() makes an asynchronous request for data. If the result of that call is necessary for the drawGraph function to perform correctly then your code isn't going to function as you might expect (though with what you've posted in the question there's no definitive indication this is the case).
The $.getJSON() function will finish executing immediately (after initiating the request), allowing drawGraph to execute, but there's no guarantee that the request will have received a response and the processing of returnedData will have occurred; in fact there's a very strong possibility that won't have happened.
You shouldn't be building an object through string concatenation like that. I'd recommend actually building up an array of objects like so:
var dataa = [];
for (var a = 0; a < 6; a++) {
var newObj = {x: + x[a], y: + y[a]};
dataa.push(newObj);
}
And then to generate the f you currently have:
var f = JSON.stringify([{data: dataa}]);
dataa = dataa + mytext;
--------------^
this is undefined initially
You need to do this -
var mytext, dataa = "", f;
In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo