How to call a javascript function with string arrays - javascript

Can anyone please tell me how to call javascript function with string arrays as argument and how to use this arrays in the called function.
Here is my code:
C# Code
for (int i = 0; i < count; i++)
{
array1[i] = dt.Rows[i]["FieldName"].ToString();
array2[i] = dt.Rows[i]["FieldValue"].ToString();
}
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"Javascript", "<script type='text/javascript'>myFunction('" + count + "','" + array1 + "','" + array2 + "');</script>");
JavaScript
function myFunction(cnt, arr1, arr2)
{
for (i = 0; i < cnt; i++)
{
alert("fname" + arr1[i] + " :fvalue " + arr2[i] + " :count:" + cnt);
}
}
any syntax error in passing array variables.

You could leverage javascript's apply method here and use arguments variable and treat it as the source of your array thereby avoiding messy 'args' on your method. You can then pass a string like:
//After ensuring all elements in array1 are wrapped in ' characters or are appropriate as arguments as-is
"myFunction.apply(this, [" + array1.join(",") + "])".
This way "myFunction" will handle ANY number of arguments or (using the javascript arguments object) array of any size. No need to pass 'count' variable. myFunction will could then be written as:
function myFunction() {
for (var j = 0, len = arguments.length; j < len; j++) {
var a = arguments[j];
//do something with a
}
}

How to call a javascript function with string arrays
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"Javascript", "<script type='text/javascript'>myFunction('" + count + "','[" +string.Join(",", array1) + "]','[" + string.Join(",", array2)+ "]');</script>");
nb : you can save the scripts tag via :
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"Javascript", "myFunction('" + count + "','[" +string.Join(",", array1) + "]','[" + string.Join(",", array2)+ "]');",true);
Also , you're adding the same key again and again ( "Javascript") :
try adding guid :
"Javascript"+Guid.NewGuid().ToString("n")

Related

Calling concatenated variables in Javascript

Is there a way to include variables in each iteration of a javascript loop? For example if I put this code into a loop
if (e1) {item_text += '{id:"' + id[1] + '",lvl:' + e1lvl + '},<wbr>'}
if (e2) {item_text += '{id:"' + id[2] + '",lvl:' + e2lvl + '},<wbr>'} // etc
and do something like
for (n = 0; n < id.length; n++) {
if (e/*concat var e w/var n?*/) {
item_text += '{id:"' + id[1] + '",lvl:' + e/*concat var e w/var n?*/lvl + '},<wbr>'
}
}
Is there a way to change the number in the var names (e1 -> e2 etc) each iteration or do i just have to keep it the long way and write everything out on its own line?
It would be possible, though highly not recommended, to use eval to come up with the variable name:
const e1lvl1 = 'foo';
const e2lvl1 = 'bar';
for (let i = 1; i < 3; i++) {
console.log(eval('e' + i + 'lvl1'));
}
But it would be better to fix your script's architecture so that this isn't necessary: put each e#lvl into an array, and then access the appropriate index of the array on each iteration:
const elvl = [
'foo',
'bar'
];
let item_text = '';
for (let i = 0; i < elvl.length; i++) {
item_text += 'lvl: ' + elvl[i] + '\n';
}
console.log(item_text);
Arrays/Objects exist in javascript for a reason! Simplify your code. There is no reason to have e1, e1l, e2... as variables. Add them to an object and access them by key, or add them to an array, and loop through them. There are many javascript functions as well that will allow you to ensure all elements match a certain condition.
function submit() {
var e = {};
var idx = 28;
for (var i = 0; i <= 24; i++) {
e[i] = {};
e[i].key = document.getElementById(`ench${i}`).checked
e[i].value = $.trim(form.elements[idx].value)
idx += 2;
}
// Check condition
if (Object.values(e).some(e => e.key)) {
//One of the checked items was true
}
}
I would agree that you should change your code to use arrays.
To answer your question though, since your e1 and e1lvl variables look to be global scope, you can access them like this
window["e1"]
window["e1lvl"]
Give this a try
for (n = 0; n < id.length; n++) {
if (window["e" + n]) {
item_text += '{id:"' + id[n] + '",lvl:' + window["e" + n + "lvl"] + '},<wbr>';
}
}

JavaScript - Printing from Array of Objects Not Working

I have this array of objects here that I am traversing and want to display a match if the person at the current index has an age within +/- 10 years of anyone else in the array. However, when I run it, it says "Cannot read property 'age' of undefined." Where did I go wrong?
function findmatches() {
var n = USERS.length;
for (var i = 0; i < n; i++) {
var currName = USERS[i].firstName;
var currAge = USERS[i].age;
var currGender = USERS[i].gender;
for (var c = 0; c < 10; c++) {
if (((USERS[c].age) + 10) <= currAge) {
document.getElementById("showmatches").innerHTML += currName + " matched to >> " + USERS[i].firstName + " " + USERS[i].lastName + " \n";
break;
}
}
}
}
What exactly is your second for loop supposed to do?
In the code you posted, it iterates through first 10 users in the USERS array. I assume it has less users than that, so at some point USERS[c] is undefined, and you're trying to access USERS[c].age.

JavaScript Looping Variables on Left Side of Equal Sign

I'm looping through results and writing them out to html.
I want to increment the number 1 on the lest side of the equal sign - the binding -
A_Inside_Bus_1_div, A_Inside_Bus_2_div, A_Inside_Bus_3_div etc..
How should I go about that?
for (var i = 0; i <= 4; i++) {
A_Inside_Bus_1_div.innerText = i + ". " + snapshot.child("0/A_Inside_Bus " + i).val();
A_Inside_Bus_1_Comments_div.innerText = snapshot.child("0/A_Inside_Bus " + i + " Comments").val();
}
Do it like this:
var A_Inside_Bus_div = [];
var A_Inside_Bus_Comments_div = [];
Before you continue the rest, like editing .innerHTML, you need to create those objects. Only after that you can do something like:
for (var i = 0; i <= 4; i++) {
A_Inside_Bus_div[i].innerText = i + ". " + snapshot.child("0/A_Inside_Bus " + i).val();
A_Inside_Bus_Comments_div[i].innerText = snapshot.child("0/A_Inside_Bus " + i + " Comments").val();
}
This is just an idea how you "should go" about that, as you said.
If those variables are actually the IDs of DIVsm and you're depending on the fact that IDs are turned into global varables, you can use document.getElementById() to access them.
for (var i = 0; i <= 4; i++) {
document.getElementById('A_Inside_Bus_' + (i+1) + '_div').innerText = i + ". " + snapshot.child("0/A_Inside_Bus " + i).val();
document.getElementById('A_Inside_Bus_' + (i+1) + '_Comments_div').innerText = snapshot.child("0/A_Inside_Bus " + i + " Comments").val();
}
Don't do this. Trying to make variable names to do what you're trying to do just leads to needlessly messy code down the road.
Stick all your elements into arrays:
var elems = [
A_Inside_Bus_1_div
A_Inside_Bus_2_div
...
];
var comments = [
A_Inside_Bus_1_Comments_div
A_Inside_Bus_2_Comments_div
...
];
Then just index the arrays:
for (var i = 0; i <= 4; i++) {
elems[i].innerText = i + ". " + snapshot.child("0/A_Inside_Bus " + i).val();
comments[i].innerText = snapshot.child("0/A_Inside_Bus " + i + " Comments").val();
}
This is an example of how you could do it with your current setup. Note though, it could be cleaned up. If each element of the elems array always has a partner in comments, it would make more sense to group them together in an object, and only have 1 array.
Also note that populating the arrays in a loop makes more sense. I just hardcoded the arrays here for the sake of brevity. I'm not sure how you're creating the elements originally. They should probably be created and put straight into the array instead of naming them and adding them later.
There are a couple ways you could go about doing this, but they tend to involve some pretty bad habits, like using eval or attaching variables to the global object so you can access them with a string:
var a = 1;
window['a']; //1
But there are better alternatives, the most common is probably storing them in equal-length arrays:
var divs = [div1, div2, div3];
var items = ['cat', 'dog', 'fish'];
items.forEach(function(element, index){
divs[index].innerText = items[i];
});
You could also look at building out a single array of objects:
var objects = [{div: div1, item: 'cat'}, {div: div2, item: 'dog'}, {div: div3, item: 'fish'}];
for object in objects {
object.div.innerText = object.item;
}

passing set of data to javascript function through jquery.html()

I have 2 function in my code - makeData and displayData -.
<script type="text/javascript">
function makeData(){
var myjson = {}; var myarray = [];
for (var i = 0; i < 10; i++){
myjson[i] = "json"+i;
myarray[i] = "array"+i;
}
//when i pass myjson[1] and myarray[1] value, it's work for me
$("#mydiv").html("<input type=\"button\" value=\"display data\"
onclick=displayData(\""+myjson[0]+"\",\""+myarray[0]+"\") />");
/*but when i tried to pass the json and array object, i got problem here.
displayData() function cannot read those objects*/
$("#mydiv").html("<input type=\"button\" value=\"display data\"
onclick=displayData(\""+myjson+"\",\""+myarray+"\") />");
}
</script>
<input type="button" value="make some button" onclick="makeData()" />
<div id="mydiv"></div>
<div id="dataDisplay"></div>
how can i pass array / json object to javascript function that write using innerHTML ???
note : my purpose is to pass set of data to javascript function.
edit : i think now it is more clearly now. sorry about before..
You can convert your object or array to a string representation (JSON) to write it in the DOM (e. g. as param for a function you call onclick).
Give me 10 min to write a better example.
Here it is. It's not perfect (e. g. indexes seem to be of type "string" even if actually are "number") but it should cover most cases. Note that you cannot convert functions or references with this example:
function convertObjectToString( obj )
{
var stringRep = "{";
for ( var index in obj)
{
var cIndex;
if ( typeof index == "number" ) // int index
cIndex = index;
else // string index
cIndex = "\"" + index + "\"";
if ( typeof obj[index] == "object" )
stringRep += cIndex + ":" + convertObjectToString(
obj[index] ) + ","; // convert recursively
else if ( typeof obj[index] == "number" )
stringRep += cIndex + ":" + obj[index] + ",";
else
stringRep += cIndex + ":\"" + obj[index] + "\",";
}
// remove trailing comma (if not empty)
if ( stringRep.length > 1 )
stringRep = stringRep.substr(0, stringRep.length - 1);
stringRep += "}";
return stringRep;
}
Or better just use the JSON.stringify function! https://developer.mozilla.org/En/Using_native_JSON/
i think i've already found the answer of my problem. and this is the modified code :
function buatdata(){
var myjson={};
var myarray= [];
for(var i = 0 ; i < 10 ; i++){
myjson[i] = "json"+i;
myarray[i] = "array"+i;
}
var arraystring = myarray.toString().replace(\,\g,",");
var jsonstring = JSON.stringify(myjson).replace(\"\g,""");
/* i changed " to ' to wrap parameter that i passed in tampildata() function
and i convert those object to string first.*/
$("#tombol").html("<input type=\"button\" value=\"display\"
onclick=tampildata('"+jsonstring+"','"+arraystring+"') />");
}
function tampildata(getjson,getarray){
//i changed string that i passed back to object, so i get what i want.
var myarray = getarray.split(',');
var myjson = JSON.parse(getjson);
}
with that function, i pass array and json object through. but i still hope there is other method i can use.
because i'm affraid if my set of data very big, it can slow the proses.

Function to number array elements outputs "undefined"

I want to number each item in an Array, like this:
["hello", "hi", "hey"].number()
> ["1. hello", "2. hi", "3. hey"]
Here's my code:
Array.prototype.number = function () {
var tempNum = this;
for (i in this) {
tempNum[i] = tempNum[(i + 1)] + ". " + tempNum[i]
}
return tempNum;
}
But this is the output:
["hello", "hi", "hey"].number()
> ["undefined. hello", "undefined. hi", "undefined. hey"]
Why? How should I implement this and why is my code not working?
I think you want something like this:
for(var i=0, len = this.length; i<len; i++){
tempNum[i] = (i + 1) + ". " + tempNum[i];
}
you're using tempNum when you shouldn't be in the right side of your equation. The reason you're getting "undefined" is because at some point in your current equation you're getting an index outside of the length of your array.
The ES5 way:
Array.prototype.number = function () {
return this.map( function ( value, i ) {
return ( i + 1 ) + '. ' + value;
});
};
Live demo: http://jsfiddle.net/XSYTK/1/
You'll need to shim .map() for IE8.
Inside your for loop, you're doing:
tempNum[i] = tempNum[(i + 1)] + ". " + tempNum[i]
If you just want to add numbers before each value, why are you getting tempNum[(i + 1)]?
It should look like:
Array.prototype.number = function () {
var tempNum = this;
for (var i in this) {
tempNum[i] = (parseInt(i,10) + 1) + ". " + tempNum[i];
}
return tempNum;
}
Note the parseInt(i,10)+1. This adds one to the index (after converting it to an int), and then prepends that to the string.
tempNum[(i + 1)] is not what you want to do, you want something like (i + 1). This also don't work, because keys are always strings. To type cast them to a float you can use (parseFloat(i) + 1) or, what is nicer, (~~(i) + 1). The total code become:
Array.prototype.number = function () {
var tempNum = this;
for (i in this) {
tempNum[i] = (~~(i) + 1) + ". " + tempNum[i]
}
return tempNum;
};
console.log(["hello", "hi", "hey"].number());
// > ["1. hello", "2. hi", "3. hey"]
I would not try to modify the array values itself when invoking the number() function, because if you invoke the function again on the same array the numbering gets doubled. Instead better make a new array and return it like this:
Array.prototype.number = function () {
var ret=[];
var len=this.length;
for(var i=0;i<len;i++){
ret.push((i+1)+'. '+this[i]);
}
return ret;
}
console.log(["hello", "hi", "hey"].number());
Demo: http://jsfiddle.net/LcHsY/
The problem with your current solution is that in each iteration, i holds the value of the element, instead of the index.
So, when you do things like
tempNum[(i + 1)]
you are trying to add "hello" and 1, and this gives an undefined result.
So, in order to get your code working you could change your code as follows:
Array.prototype.number = function () {
var tempNum = this;
for (var i = 0; i < tempNum.length; ++i) {
tempNum[i] = (i + 1) + ". " + tempNum[i]
}
return tempNum;
}

Categories

Resources