i want to for loop my array result as array because i use nested loop.
Here is my code
var isp = ["yahoo", "gmail"];
var yahoo = ["#yahoo.com", "#rocketmail.com", "#ymail.com"];
var gmail = ["#gmail.com"];
for(x=0;x<isp.length;x++){
//Should alert 3 Because var yahoo contains 3 element
//Should alert 1 because var gmail is contain 1 element
alert(isp[x].length);
for(y=0;y<isp[x].length;y++){
//Should alert #yahoo.com, #rocketmail.com and so on
alert(isp[x][y]);
}
}
Here is my JSFiddle https://jsfiddle.net/4v272ghL/1/
Try this:
https://jsfiddle.net/4v272ghL/2/
var isp = ["yahoo", "gmail"];
var providers = {
'yahoo': ["#yahoo.com", "#rocketmail.com", "#ymail.com"],
'gmail': ["#gmail.com"]
};
isp.forEach(function(v, i) {
console.log(v);
providers[v].forEach(function(domain, index) {
console.log(domain);
});
});
You're using a JS object to hold the arrays of domains instead. Using this, you can access each provider's data dynamically.
Maybe you don't need so many arrays? Lets use an object instead.
var isps = {
yahoo: ["#yahoo.com", "#rocketmail.com", "#ymail.com"],
gmail: ["#gmail.com"]
};
for(isp in isps) {
var providers = isps[isp];
document.write(isp + " has " + providers.length + " provider(s):<br/>");
providers.forEach(function(domain) {
document.write(domain + "<br/>");
});
};
This works because instead of looping through an array and trying to access different variables with the same name, you can instead simply loop through the keys of an object (which are the same as that first array) and use it to access the values of that object (which are the same as in the other variables you had before).
Note that I've changed your alerts to things that will be more informative in running the code snippet. Of course, once you've got access to these values isp, providers and domain, you can do whatever you like with them - you don't need to document.write them.
There are a few benefits to this method. For instance, as we're only human, what if this happened:
var isp = ["yahoo"];
var yahooo = ["#yahoo.com"];
There's a dependency on the values in isp and the variable names being exactly the same. A simple error like above ("yahooo" instead of "yahoo") would prevent the code from working, and a one letter bug like that could be quite difficult to find if you don't know what you're looking for.
If you're to come back and add or modify these values often, this could become a concern. With the object pattern, it's cleaner and more self-contained.
One potential concern with this solution, however, is if the order in which these providers are looped through is important (i.e. if you always need "yahoo" to output before "gmail"). Currently JavaScript states the following in regards to objects: "It is an unordered collection of properties". This could be subject to change in ES6 (we're currently on ES5). Read more about this particular issue here:
Does JavaScript Guarantee Object Property Order?
You will need to eval the isp[x] in order to get the array names of the other two. For example:
var isp = ["yahoo", "gmail"];
var yahoo = ["#yahoo.com", "#rocketmail.com", "#ymail.com"];
var gmail = ["#gmail.com"];
for(x=0;x<isp.length;x++){
//Should alert 3 Because var yahoo contains 3 element
//Should alert 1 because var gmail is contain 1 element
alert(isp[x].length);
for(y=0;y<eval(isp[x]).length;y++){
//Should alert #yahoo.com, #rocketmail.com and so on
alert(eval(isp[x])[y]);
}
}
This is clear i guess right ?
:D
var ispAndData = [
["yahoo", ["#yahoo.com", "#rocketmail.com", "#ymail.com"]],
["gmail", ["#gmail.com"]]
];
for (x = 0; x < ispAndData.length; x++) {
//Should alert 3 Because var yahoo contains 3 element
//Should alert 1 because var gmail is contain 1 element
document.write(ispAndData[x][0] + " -> ");
document.write(ispAndData[x][1].length + "</br>");
for (y = 0; y < ispAndData[x][1].length; y++) {
//Should alert #yahoo.com, #rocketmail.com and so on
document.write(ispAndData[x][1][y] + "</br>");
}
document.write("</br>");
}
Related
The point is I'm not an expert with JS so excuse me if my code is a big mistake, in fact I'm just training to learn making a huge "Frankenstein" from a research around the web.
I want to take two set or lists of values input by the user and compare them looking for matches with js and jquery.
First, I take the values from two groups of inputs (diferenced by class) with .map(), this to have the values to create the arrays.
var x = $(".row_a").map(function() {
return this.value;
}).get();
var y = $(".row_b").map(function() {
return this.value;
}).get();
Then I'm traying to create one variable that contain the two arryas separatly (here Is when think I have the problem) if I "hardcode" the arrays the next part of the script works as expected, but if I use the the first two variables made above, the script just crash.
var arrays = [
[x],
[y]
];
In the third part (I really don't understand this part of the code in deep) I run the script that compare the two arrys on the second variable and then append a paragraph with the result.
var result = arrays.shift().reduce(function(res, v) {
if (res.indexOf(v) === -1 && arrays.every(function(a) {
return a.indexOf(v) !== -1;
})) res.push(v);
return res;
}, []);
$(".match").append("<div>Numbers " + result + " match in both lists</div>");
Somebody can help me to undersnatd whats wrong or giveme a clue or link that can help?
curious: if I use the same variable twice in the variable that contain the arrays, the script works and finds four matches (I think is right becouse compare the same array)
DEMO
--
EDITED:
Thanks to #KarlReid and #Potorr. I didn't know the intersection concept in javascript, so now I know a better way to achive the result. I'll read more about it to try understand the answer in deep.
Thanks to #Alexandru for letting me know the sintax error, it'll be very basic and usefull henceforth.
Final Result: DEMO
(I'll be edit the tittle of the post to try improve the search for others with the same question in the future.)
This works, explanation in-line:
$(".action").click(function() {
var x = $(".row_a").map(function() {
return this.value;
}).get()
var y = $(".row_b").map(function() {
return this.value;
}).get()
// this is not really needed, if you want it:
// x, y are already arrays, so you don't need to wrap them with []
// var arrays = [
// x,
// y
//];
// intersection, adapted from: https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript
// if you use the "arrays" variable, then change x to arrays[0] and y to arrays[1]
//var intersection = x.filter(function(n) {
// return y.indexOf(n) !== -1;
//});
// the intersection function posted by #KarlReid is actually better and faster:
var intersection = x.filter(Set.prototype.has, new Set(y));
// create the result string
var result = intersection.join(',')
$(".match").append("<div>Numbers " + result + " match in both lists</div>");
});
Edit: Changed intersection function to the one posted by #KarlReid
Although better solutions exists, as pointed out by comments the Potorr's answer, the only problem with the code posted is this:
var arrays = [
[x],
[y]
];
x and y are already arrays, so you don't need to wrap them with [ ]. The code works if you simply replace the above code with:
var arrays = [
x,
y
];
Updated demo
How change strings in javascript arrays. I want to change array codes to strings.
How change strings in javascript arrays. I want to change array codes to strings.
How to get this;
var _0x1576 = ["SayHello", "GetCount", "Message : ", "You are welcome."];
function NewObject(_0x7aa7x2) {
var _0x7aa7x3 = 0;
this.SayHello = function (_0x7aa7x4) {
_0x7aa7x3++;
alert(_0x7aa7x2 + _0x7aa7x4);
};
this.GetCount = function () {
return _0x7aa7x3
};
}
var obj = new NewObject("Message : ");
obj.SayHello("You are welcome.");
from;
var _0x1576 = ["SayHello", "GetCount", "Message : ", "You are welcome."];
function NewObject(_0x7aa7x2) {
var _0x7aa7x3 = 0;
this[_0x1576[0]] = function (_0x7aa7x4) {
_0x7aa7x3++;
alert(_0x7aa7x2 + _0x7aa7x4);
};
this[_0x1576[1]] = function () {
return _0x7aa7x3
};
}
var obj = new NewObject(_0x1576[2]);
obj.SayHello(_0x1576[3]);
EDIT: So you have some code, where all the variable names have been replaced by numbers or indices into this global array of names, and you would like to be able to read it. There is already an answer to this question, which contains links to a bunch of useful deobfuscation tools.
Your case here looks fairly trivial - it appears that you could just do a string search and replace, substituting in the array value every time it is indexed. The regexp /_0x1576\[(\d+)\]/g should find everything that accesses the variable _0x1576 with an integer index. The inner group (\d+) should give you the index with which it was found. You could use something like this to do deobfuscate your source. However, some of the names have been lost in the obfuscation process; i.e. the name of the parameter 0x7aa7x4 in the SayHello function can't be restored. You will have to read the method, understand what its' purpose is, and try to come up with a meaningful name yourself.
One question though - just how much code do you have like this? If there are only a few names in the array of strings, then #Nina Scholz's suggestion seems fairly reasonable. Just go through them one by one, in a text editor, and use the 'Find and Replace' functionality.
I'm trying to dynamically find a particular value inside a multi dimensional object.
To create the object, I'm doing this:
var inViewElements = {};
$('.story-section')
.each(
function(index){
var sectionId = 'story-section-' + Math.floor(Math.random() * (1000 - 1 + 1)) + 1;
$(this).attr('id', sectionId);
var inViewHeight = $(this).height(),
inViewPosTop = $('#' + sectionId).offset().top,
inViewPosBottom = ((inViewPosTop + inViewHeight) - (inViewTolerence + inViewHeight));
inViewElements[inViewPosTop] = {
id: sectionId,
height: inViewHeight,
bottom: inViewPosBottom
};
debug('Inview', 'Object', sectionId);
debug('Inview', 'Height', inViewHeight);
debug('Inview', 'Offset Top', inViewPosTop);
debug('Inview', 'Offset Bottom', inViewPosBottom);
}
);
console.log(inViewElements);
And the output looks like:
What I'm trying to do is compare if another variable value, for example:
var currentPos = '3038';
Matches any of the objects keys. E.g. the 3038 or 2038 etc.
I'm struggling to figure this one out!
So you're trying to search for an object that contains a certain value?
There is no way to query an array/object in Javascript. As you're not using incremental indexes, I would suggest using a foreach loop, using a conditional statement to check whether the property you're trying to match is equal to the value you're looking for.
It would be quicker to use a for loop, however that would require incremental indexes.
If you r logging response variable through which ur output came then u can use this function
for(var x in response){
if( x == 3038) {
// do something
}
}
or
for(var x in response){
if(x == currentPos){
//dosomething
}
}
can u give me the proper code of how u put values to console log so i will edit the answer properly accourding to your question
I am writing a page that collects serial numbers for parts installed in an assembly. I want to validate the user input on the client-side, if I can.
So if I have multiple dense arrarys, how can I refer to them using a varaiable? For instance, say I have three densely packed arrays who's names represent part numbers, and who's values represent serial numbers (that have been consumed in other assemblies).
arr_PN-123-ABC = ('SN0123','SN0124','SN0125')
arr_PN-456-DEF = ('SN00333','SN00334','SN00335')
arr_PN-789-GHI = ('SN-0001','SN-0002','SN-0003','SN-0004')
function fcnValidateSN(_givenPN, _givenSN) {
//make sure the given values are not null or empty...
//derive the array of serial numbers that coorsponds to the given part number...
var vArrName = "arr_" + vGivenPN;
//loop thru the array of serial numbers to determine if the given sn was already used...
for(var x=0; x < vArrName.length(); x++) {
if(vArrName[x]==_givenSN) {
alert("Serial number '" + _givenSN + "' was already used in another assembly.");
theForm.txtPN.focus();
return;
}
} //end 'for' loop
} //end fcnValidateSN()
So the problem is that 'vArrName' is a string with a value of 'arr_' instead of a refernece to an array who's name is 'arr_'.
I tried wrapping it with the eval() function, but eval() treats dashes as minus signs.
One other note: I cannot use jquery for this effort.
Thank you
You cannot generate a reference to a variable declared with var (except see below). You can use dynamic property names to refer to properties of objects, so:
var arrays = {
"arr_PN-123-ABC": ['SN0123','SN0124','SN0125'],
"arr_PN-456-DEF": ['SN00333','SN00334','SN00335'],
// ...
};
Then:
console.log( arrays["arr_PN-" + num + "ABC"][0] ); // SN0123
Note that you cannot use "-" in a variable name, but you can use it in an object property name.
The exception to not being able to access var variables by dynamic name is made for global variables in a browser. Those variables all end up as properties of the window object.
An array in JavaScript is delimitated by [ and ], not ( or ).
A valid JavaScript variable name can't contain '-'
The length property of an array isn't a function
Well, I've done some (actually, a lot of) adjustments in your code, but I think this is what you need:
var serialGroups = {
PN_123_ABC: ['SN0123','SN0124','SN0125'],
PN_456_DEF: ['SN00333','SN00334','SN00335'],
PN_789_GHI: ['SN-0001','SN-0002','SN-0003','SN-0004']
};
function validateSerial(groupName, sn) {
var serials = serialGroups[groupName];
for(var i=0; i < serials.length; i++){
if(serials[i] == sn) {
alert("Serial number '" + sn + "' was already used in another assembly.");
//Do whatever you want here
return;
}
}
}
Use a single object that has the arrays as elements:
var arr_PN = {
'123-ABC': ('SN0123','SN0124','SN0125'),
'456-DEF': ('SN00333','SN00334','SN00335'),
'789-GHI': ('SN-0001','SN-0002','SN-0003','SN-0004')
}
And then reference using:
var vArrName = arr_PN->{vGivenPN};
I am working on an educational tool. I want to retrieve a value from one of a group of arrays based on a parameter passed to a function. Specifically, this goal of this code is to change the label text on a group of radio-buttons based on selections by a user.
Here's my code:
//arrays
var bodyplan = ['Anguilliform', 'Compressiform', 'Depressiform', 'Filiform', 'Fusiform', 'Globiform', 'Sagittiform', 'Taeniform']
var caudalshape = ['Continuous', 'Emarginate', 'Forked', 'Lunate', 'Rounded', 'Truncate']
var mouthposition = ["Inferior", "Jawless", "Subterminal", "Superior", "Terminal"]
//function
function changelabels(opt1, opt2){
var i = opt2
var c = 1
var index = 0
while (i>=c){
document.getElementById("rb" + c + "lbl").innerHTML = (opt1[index])
c = c + 1
index = index + 1}}
The call to the function is made in a switch statement that is quite lengthy. For example here is one of the calls:
case 4:
changelabels("caudalshape", 6)
The code I created above does change the labels, but not in the desired way. For the above case instead of my radio-buttons being labeled "Continuous", "Emarginate", "Forked" and so on, they are labeled "c", "a", "u", "d" and so on. In other words the function I wrote is not pulling values from the array. It is simply selecting letters from the parameter word passed tot he function according to the index.
Any help would be appreciated. I'm a relative novice at Javascript. I've been trying to tackle this problem for several hours both in playing with code and in searching these forums.
This is because you're operating on the string "caudalshape" rather than the array which is pointed to by the variable named "caudalshape".
You can fix this by passing the array rather than the string;
changelabels(caudalshape, 6)
Unrelated to your problem; you should really start adding your own semi-colons to your code. Yes, it's optional in JavaScript, but it's not in many others, and it's a pain to adjust to when the time comes to learn another language (personal experience). For more info, see Do you recommend using semicolons after every statement in JavaScript?
Unless I'm missing something in your implementation, you want to pass in the caudalshape variable rather than the string:
case 4:
changelabels(caudalshape, 6)
1st there are some redundant code, which i am removing for your refrence. and also your missing semicolon everywhere.
//arrays
var bodyplan = ['Anguilliform', 'Compressiform', 'Depressiform', 'Filiform', 'Fusiform', 'Globiform', 'Sagittiform', 'Taeniform'];
var caudalshape = ['Continuous', 'Emarginate', 'Forked', 'Lunate', 'Rounded', 'Truncate'];
var mouthposition = ["Inferior", "Jawless", "Subterminal", "Superior", "Terminal"];
//function
function changelabels(opt1, opt2){
var index = 0;
while (index < opt2){
document.getElementById("rb" + (index+1) + "lbl").innerHTML = opt1[index];
index = index + 1;
}
}
Here are the correction: : the parameter you are passing is string, you should pass array variable
case 4:
changelabels(caudalshape, 6);