How can I assign null value to an array element? - javascript

I am facing too small problem, could you give me idea how to solve that.
for(var j=cArray.length-1;j>=0;j--)
{
if(cArray[j]=='.') {
cArray[j]='';
break;
}
else{
cArray[j]='';
}
}
I wrote this for loop in javascript.NULL value is not assigning to array element.
At last i am getting what is the content in cArray[j] only.I can't able to change that value.My declaration is correct or not?

What are you trying to accomplish?
What the code does in this form is that it makes all elements in an array '' (empty) that are after the last '.' element.
If you just want to truncate the array you could do somethink like this:
var jsArray = ['H','e','l','l','o','.','w','o','r','l','d'];
jsArray.length = 5;
alert(jsArray.length); // returns 5

Your code is right. Maybe it is empty? See my demo and observe as it works =)

To truncate the array at the first .:
for(var j=cArray.length-1;j>=0;j--)
{
if(cArray[j]=='.') {
cArray.length = j;
break;
}
}
Or, if the array is really just a string:
var myString = "1.1.1";
var result = myString.split(".");
var firstPart = result[0];
firstPart now contains 1.

Related

Get length of longest String in Array

i need to find out the longest string of an array. First of all i push different "text" elements into my array, since the stringe and amount of those "text" elements can differ from case to case. (they are lables of an chart and thus are generated based on the charts sections.
my code right now looks like this:
var textLengthArray = [];
domContainer.find(" g > .brm-y-direction > .tick > text").each(function () {
textLengthArray.push($(this));
});
var lgth = 0;
var longestString;
for (var i = 0; i < textLengthArray.length; i++) {
if (textLengthArray[i].length > lgth) {
var lgth = textLengthArray[i].length;
longestString = textLengthArray[i];
}
}
It already pushes all text elements into my array. But when i use
alert(longestString.length)
i allway get "1" as a result. I am pretty shure i have to add .text anywhere before .length, since the code does not check die textlength of the textelements.
Since i am quite new to javascript i would highly appreciate some help.
Thanks in advance!
textLengthArray.push($(this)); should be textLengthArray.push($(this).text()); otherwise your array consists of jQuery objects. And indeed jQuerySet has length property. And in your case the set consists of 1 element.
You are re-declaring lgth in each iteration of the array which is re-assigning the value.
Replace var lgth = textLengthArray[i].length with lgth = textLengthArray[i].length and you should be good.
I don't know about the rest of your code, looks fine. But you're pushing a jQuery object$(this), not a string. Line three should read textLengthArray.push(this);.
Apparently one of the strings your pushing is a valid jQuery selector that finds an element :-)
No need to create a separate array. Just iterate objects and update as you go:
longest = "";
$('div').each(function() {
var t = $(this).text();
if(t.length > longest.length)
longest = t;
});
alert(longest)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hello</div>
<div>wonderful</div>
<div>world</div>
To get the longest string from any array, try reduce:
a = ['hello', 'wonderful', 'world']
longest = a.reduce(function(prev, e) {
return prev.length >= e.length ? prev : e;
});
alert(longest)
Sort the array by length and get the first element. Hope it works for you
stackoverflow.com/questions/10630766/sort-an-array-based-on-the-length-of-each-element

Appending text through loop iteration

Not sure why I'm having a hard time with this. I think it's getting late in the day probably but --
I'm pulling database values into an array. The current array is: [1,3]. I'm then stepping through the array and appending a prefix to the values (in this case: "&Plantkey=") in order for the final string to have the format of:
&Plantkey=1&Plantkey=3
Here's my code so far:
if (array[a].ParameterName == "Plantkey") {
var plantKey = array[a].ParameterValue;
var plantTemp = [];
plantTemp = plantKey.split(",");
for (var p = 0; p < plantTemp.length; p++) {
var plantKeyString = ("&Plantkey=" + plantTemp[p]);
}
}
I'm only getting the last array value (&Plantkey=3). With javascript, it doesn't like me instantiating the "var plantKeyString" and adding the "+=" operator. If I instantiate the array above the for loop, like so:
var plantKeyString;
for (var p = 0; p < plantTemp.length; p++) {
plantKeyString += ("&Plantkey=" + plantTemp[p]);
}
Then I end up with a longer string, including the array values I want but it also pulls in the "undefined" value that it finds at the beginning so it looks like this:
undefined&Plantkey=1&Plantkey=3
I could easily look for the "undefined" and remove it but I'm sure the problem is with the loop iteration, not the data, obviously.
Any help would be greatly appreciated! Thanks!
The reason you are getting only the last value in the first case is because you are redeclaring a new plantKeyString for each loop hence only the last declaration stays.
with the second solution just do the following and it should work:
var plantKeyString="";
for (var p = 0; p < plantTemp.length; p++) {
plantKeyString += ("&Plantkey=" + plantTemp[p]);
}
The reason you were getting the undefined at the beginning of your final result was because 'plantKeyString' is 'undefined' as you have not given it a value. In javascript all variables are undefined till you give them a value. So in the solution that I have provided you are just instantiating it with an empty string.
You can do it in a succinctly way simply using array join() method and add &Plantkey= at first as follows:
var plantKeyString = '&Plantkey=' + array.join('&Plantkey=');
For an [1,3] array this code produces what you expect: &Plantkey=1&Plantkey=3, try with this code sample:
var array = [1,3];
var plantKeyString = '&PlantKey=' + array.join('&PlantKey=');
alert(plantKeyString);
See join() description here

Adding a javaScript array to a HTML page?

Im trying to add an array to a webpage. I have tried a few different pieces of code show below but none of them work. I would like the output to be similar to a list like:
text1
text2
text3
...
The code I have used so far is:
var i;
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList="";
for (i=0;i<test.length; i++) {
testList+= test[i] + '<br />';
}
$('#here').html('testList');
songList="";
});
I am quite new to javaScript so I am not sure if I have just made a small mistake or if Im doing this in the wrong way. Also, above is a copy of all the code in my javaScript file and some places online are saying I need to import something? Im not sure!
Thanks
Try without quotes:
$('#here').html(testList);
-or-
$('#here').html(test.join('<br />'));
Another approach:
var html = ''; // string
$.each(test,function(i,val){ // loop through array
var newDiv = $('<div/>').html(val); // build a div around each value
html += $('<div>').append(newDiv.clone()).remove().html();
// get the html by
// 1. cloning the object
// 2. wrapping it
// 3. getting that html
// 4. then deleting the wrap
// courtesy of (http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html)
});
$('#here').html(html);
There might be more code in the latter, but it'll be cleaner in the long run if you want to add IDs, classes, or other attributes. Just stick it in a function and amend the jQuery.
Try changing the line
$('#here').html('testList')
to
$('#here').html(testList)
What you have works if you remove the single quotes from testList. However, if you would like an actual unordered list you can do this. (here's a jsFiddle)
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList=$("<ul></ul>");
for (var i=0;i<test.length; i++) {
$(testList).append($("<li></li>").text(test[i]));
}
$('#here').html(testList);
songList="";
}); ​
This line:
$('#here').html('testList');
shouldn't have single quotes around testList - you want to use the content of the variable, not the string literal "testList".
Don't pass the variable as a string : $('#here').html('testList'); Pass it without quotes : $('#here').html(testList);
Here's the simplest version:
$(document).ready(function() {
var test = ["text1", "text2", "text3"];
$('#here').html(test.join("<br>"));
});

Global var in JavaScript

This is annoying me.
I'm setting an array in beginning of the doc:
var idPartner;
var myar = new Array();
myar[0] = "http://example.com/"+idPartner;
And I'm getting a number over the address, which is the id of partner. Great. But I'm trying to set it without success:
$.address.change(function(event) {
idPartner = 3;
alert(idPartner);
}
Ok. The alert is giving me the right number, but isn't setting it.
What's wrong?
Changing the value of the variable does not re-set the values within the array. That is just something javascript can't do automatically. You would have to re-generate the array for it to have the new id. Could you add the id to the value where you use the array instead of pre-setting the values in the array containing the id?
Edit: For example, you would do:
var myArray = [];
var myId = 0;
myArray[0] = "http://foo.com/id/";
and when you need to use a value from the array, you would do this:
var theVal = myArray[0] + myId;
Try this:
var myvar = ["http://site.com/"];
$.address.change(function(event) {
myvar[1] = 3;
}
then use myvar.join () where you need the full url.
The problem here is that at the line
myar[0] = "http://site.com/"+idPartner;
..you perform a string concatenation, meaning you copy the resulting string into the array at index position 0.
Hence, when later setting idPartnerit won't have any effect on the previously copied string. To avoid such effect you can either always construct the string again when the idPartnervariable updates or you create an object and you evaluate it when you need it like...
var MyObject = function(){
this.idPartner = 0; //default value
};
MyObject.prototype.getUrl = function(){
return "http://site.com/" + this.idPartner;
};
In this way you could use it like
var myGlblUrlObj = new MyObject();
$.address.change(function(event){
myGlblUrlObj.idPartner = ... /setting it here
});
at some later point you can then always get the correct url using
myGlblUrlObj.getUrl();
Now obviously it depends on the complexity of your situation. Maybe the suggested array solution might work as well, although I prefer having it encapsulated somewhere in an object for better reusability.
myar[0] = "http://site.com/" + idPartner;
After this line, myar[0] = "http://site.com/undefined" and it has nothing to do with the variable idPartner no more.
So, after that changing the value of idPartner will affect the value of myar[0].
You need to change the value of myar[0] itself.

How can I find the length of a specific index in an array

have tried various things
split[6].length
String.split[6].length
along these lines without success get this error message for the last one ...
ReferenceError: "string" is not defined.
Hi Thanks for all the replies, in the end I created an array based on the index of the original array and then queried the length of that. As you can see I am having trouble removing single and double quotes from the input strings. New to javascript and its making me a little crazy lol.
// Loop through all the input messages
for (var i = 0; i < input.length; i++) {
var next = output.append(input[i]);
// Get the body of the current input message
var body = input[i].text;
// Set the body
next.text = body ;
next.text.replace(/\'/g, "'");
next.text.replace(/\"/g, """);
//replace(/['"]/g,'');
// Set a property
var split = next.text.split(",");
var array1 = split[5];
var array2 = split[2];
next.setProperty("aaaLength", split.length);
next.setProperty("aaaSplitValue", split.length);
next.setProperty("aaaArray1Value", split.length);
next.setProperty("aaaArray2Value", split.length);
if (next.getProperty("BaseFilename")=="name"){
next.text.replace(/\'/g, "'");
next.text.replace(/\"/g, """);
//replace(/['"]/g,'');
if(split.length>10){
next.setProperty("FullFilename","nameError"+i);
next.setProperty("BaseFilename","nameError"+i);
next.setProperty("Suffix",".err");
}
if(array1.length>10){
next.setProperty("FullFilename","nameSnameSuffixError"+i);
next.setProperty("BaseFilename","nameSnameSuffixError"+i);
next.setProperty("Suffix",".err");
}
}
Length should work if the elements are strings. See the following in action at http://jsfiddle.net/46nJw/
var parts = "foo,bar,baz,foop".split(/,/);
alert( parts[3].length ); // should alert 4
var arr = ['one','two','three']
arr[1].length
returns 3
Are you sure it is returning a string?
You can force it to convert to a string like so:
String(split[6]).length;
I don't know what you need, so I give you all the options I can think of:
var commaSeparatedString = "one, two, three";
var str = commaSeparatedString.split(",");
alert (str.length) // outputs '3'
alert (str[2]); // outputs 'three'
alert (str[2].length); //outputs '5'

Categories