Printing output in console.log for a function - javascript

I have a javascript that I am using to pull id of a tag . But due to some limitation on a platform where I need to use this I have to make this script under function so I will get the output in return. I am trying but I am failing to get it.
This is the script I have;
var arr2st3 = [].map.call(document.querySelectorAll('article:nth-child(-n+4)'), function(el) {
return el.id.replace(/[^\d]/g, '');
});
This is what I am trying to come up;
function myfun() {
var arr2st3 = []
var arr2st3 = arr2st3.map.call(document.querySelectorAll('article:nth-child(-n+4)'),
function(el) {
return el.id.replace(/[^\d]/g, '');
});
return;
console.log(myfun);
}
This is the test url -> https://jsfiddle.net/v3d0nz9d/
I need to get output in return as ['123456', '7896669', '1147777']
Any help would be highly appreciated.
TIA

[].map is shorthand for Array.prototype.map, so you don't need to store that in a variable, you can just return the return value of your map. Anything after a return statement won't be called, so your console.log is never reached. Also, to log the values returned from your function, you need to call it in your console.log.
function myfun() {
return [].map.call(document.querySelectorAll('article:nth-child(-n+4)'), function(el) {
return el.id.replace(/[^\d]/g, '');
});
}
console.log(myfun());

Related

Return value in JavaScript using variable name

I made a function in my JavaScript, here is the scene:
Please note, the code below is just for my scenario, its not working.
getData('bill', 'userAge');
Function getData(u, variable) {
fetch(`url`).then(r=> { return response.json();})
.then(u => {
var userFullName = u.fullname;
var userAge = u.age;
var userGender = u.gender
return variable
});
}
when I execute the function getData('bill', 'userAge') which userAge is the variable name inside the function. And the function will return the value from variable name: userAge inside the function, so I dont have to write another code like, if(variable=='userAge') return userAge;
Is it possible ? Just asking, because I have ton of variables in my function, for now I'm still using if(variable=='userAge') return userAge
Well, answering directly your question: No, if you want to return exactly with the variable you are passing right now, you'll need to map each variable name to each return property.
BUT, if you pass directly and exactly the name of the property as variable parameter, then you can just use return u[variable]. For Example, instead of passing userFullName, you pass just fullname.
I'm not going to enter in the merit that your current example code being completely wrong because Function ... is not going to work since you should use function ..., but here below I made a functional example using a different approach to the fetch using await and async, you can see that it's returning the property I specified, which is "title".
async function getData(variable) {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', {});
const u = await response.json();
return u[variable];
}
getData('title').then(a => {console.log(a)});
To check if my example returned the expected property from the object, you can access the link: JSON Example
One solution:
getData('bill', 'age');
function getData(u, variable) {
return fetch(`url`).then(r=> { return r.json();})
.then(u => {
return u[variable];
});
}
If you must use different names in your variable parameters than in your u properties, you can map them rather than use if/switch:
paramToVariable = {
userAge: 'age',
...
};
...
return u[paramToVariable[variable]];
Or you may use a function to map rather than an object.

getText does not return the value, but returns Object Object when I setValue

So I have the following problem at hand;
I want to getText from a registrationNumber. so I defined a var regNumber = null;
I defined the var in global.js because I want to access the var throughout the whole test with different pageObjects and outside of a specific function.
When it gets the text and it needs to fill in the text with setValue in the Template Search it returns Object Object, so I tried to use toString but is the same.
this is the function which I need to use in order to use the var
module.exports = {
var regNumber = browser.globals;
Page Object
openSearch: function(browser, regNumber ) {
browser.perform(function () {
browser.waitForElementVisible('.registrationnumber-search input', 3000)
browser.setValue('.registrationnumber-search input', regNumber )
return this;
})
Test
.continueButton()
browser.getText('xpath', '//*[#id="wizardDetailsTab"]/div[1]/div/div[1]/h4/span[2]', function (result) {
regNumber = result.value
console.log(result.value)
})
certificateEditor
.quickMenu("Permit")
.createNewItem("template")
permit
.openSearch(browser, regNumber)
The console.log(result.value) returns the value which I want, however it does not work when I want to use that value in setValue. If I create a function and do the getText in that scope, it fills in what I need. BUt I want to know why it does not work when I try it like this.
Thanks in advance!
in your page object :
openSearch: function(regNumber ) {
return this.perform(function (done) {
this.api.waitForElementVisible('.registrationnumber-search input', 3000)
.setValue('.registrationnumber-search input', regNumber )
done(); //prevent timeout issue
})
Move the code after getText() into it.
var permit=client.page.permit() // replace .permit() as .yourpageobjectjsname()
.....
.continueButton()
browser.getText('xpath', '//*[#id="wizardDetailsTab"]/div[1]/div/div[1]/h4/span[2]', function (result) {
regNumber = result.value
console.log(result.value)
certificateEditor
.quickMenu("Permit")
.createNewItem("template")
permit
.openSearch(regNumber)
})
From the looks of it what's happening is you're returning an Object, when you're looking for a string. I think you just need to designate the object you want.
browser.globals
should be something like
browser.globals.value or browser.globals.text
Your browser.globals is the object being returned. You have to specify what key/value pair you want that object to return.

Why doesn't calling a function from an object work in this for loop?

Edit: Problem solved, I forgot to put the output for the riteg object before.
Okay, so I'm quite sure how to describe this issue (which is why the title is bad), but this for loop:
function(){
var out = 0;
for(var i = 0;i<gameLists.listAllGen.length;i++){
out += window[gameLists.listAllGen[i]].output();
}
return out/10000;
},
doesn't work at all. In the console, it says: TypeError: window[gameLists.listAllGen[i]].output is not a function
When I replace the [i] with, for example, [0], it works:
function(){
var out = 0;
for(var i = 0;i<gameLists.listAllGen.length;i++){
out += window[gameLists.listAllGen[0]].output();
}
return out/10000;
},
returns out as expected and no errors.
The variables if needed:
var gameLists = {
listAllGen:['solarGen','riteg']
}
and
var solarGen = {
name:"Solar Generator",
count:0,
genRate:0.25,
price:410,
output:
function(){
return this.count*this.genRate*10000;
},
gameLists.listAllGen[0] returns -> solarGen
and you have solarGen in your script, thus window[gameLists.listAllGen[0]].output() referes to the output key and () calls the function assosiated with the key solarGen
But gameLists.listAllGen[1] return -> riteg
and no output property is assosiated with the riteg, thus it, and window[gameLists.listAllGen[1]] it expects. that there is riteg with output as a key aand a function assosiated with it, but it is not able to find that.
Thus you are getting the error
TypeError: window[gameLists.listAllGen[i]].output is not a function
because there is no function by that name.

How to get input from Chrome's Javascript console?

Is there a way to programmatically get input from the Javascript Console of Google Chrome, similar to readline() in Firefox?
A tricky way to do this is assigning a getter to a property of a window object
Object.defineProperty(window, 'customCommand', {
get: function() {
console.log("hey");
return "hey";
}
});
So when you type "customCommand" (without parenthesis) it will print your console.log text to the console while the console is "getting" the variable.
You will still have to return something though, and I'm not sure how you could change the order so that the value is returned first and the text in the console appears second. It's definitely possible though, I've seen this happen.
This is an indirect method of taking inputs:
Declare a function in JavaScript:
function your_command_here() {
//code
}
As Chrome's console basically provides methods for communicating with the page's contents, like JavaScript variables, functions, etc., so declaring a function as a receivable command can be an option.
In the console, for providing input, the user shall type:
your_command_here()
Another workaround is:
Declare a function:
function command(var cmnd) {
switch(cmnd) {
case "command1":
//code
break;
}
}
So the user can (more conveniently) type:
command("user's command here")
We can do is hook the console.log so whenever it logs something we can access, otherwise there is no such direct method as like in firefox which does this possible for us in a simple single line code.
var tempStore = [];
var oldLog = console.log;
console.log = function() {
tempStore.push(arguments);
oldLog.apply(console, arguments);
}
You might need to incorporate jsh (Javascript Shell) in your environment if you are working with console IO. See http://code.google.com/p/jsh/ for the how-to. Hope this helps.
Sorry, doesn't work on Chrome JS Console, just works on the repl from repl.it
Example from repl.it:
console.log("Enter your name:");
console.read(function(name) {
console.log('Your name is ' + name + '.');
});
Here is a solution to input from the console.
Try this out!!
process.stdin.resume();
process.stdin.setEncoding('ascii');
var stdInput = "";
var stdInputArr = "";
var index = 0;
process.stdin.on('data', function (data) {
stdInput += data;
});
process.stdin.on('end', function () {
stdInputArr = stdInput.split("\n");
main();
});
// Reads complete line from STDIN
function readLine() {
return stdInputArr[index++];
}
//call this function in the main function
javascript node.js jquery consoleweb
The better you can do is use:
myVar = prompt('Which value do your want?')

Jquery return value

I used a code:
jQuery.fn.MyFunction = function(){
return this.each(function() {
attributes = "test";
return attributes;
});}
But when I call
var1 = $(this).MyFunction();alert(var1);
I got an [object], but not the "test".
How to allow jquery plugin return a some value?
jQuery plugins are generally designed to return a jQuery object so you can chain method calls:
jQuery("test").method1().method2() ...
If you want to return something else, use the following syntax:
jQuery.fn.extend({
myFunction: function( args ) {
attributes = "test";
return attributes;
}
});
, or access it via its index using [].
Here is once again your code:
jQuery.fn.MyFunction = function() { #1
return this.each(function() { #2
return "abc"; #3
}); #4
}; #5
Now let's check what every line do.
We declare property MyFunction which is a function for every jQuery object.
This line is first and the last statement of jQuery.MyFunction(). We return the result of this.each(), not the result of lambda-function (used as a argument for jQuery.each()). And this.each() returns itself so the final result is that you get jQuery object returned.
Lines 3-5 are not important in fact.
Just consider those two examples:
jQuery.fn.MyFunction = function() {
return this.each(function() {
return "abc";
});
};
jQuery.fn.AnotherFunction = function() {
return "Hello World";
};
var MyFunctionResult = $(document).MyFunction();
var AnotherFunctionResult = $(document).AnotherFunction();
alert(MyFunctionResult);
alert(AnotherFunctionResult);
I believe jQuery returns the object, so you can maintain the chainability of diffrent functions.
Hmm, perhaps use
var1 = $(this)[0].MyFunction();alert(var1);
But I'm not sure if that is what you want or if your code works at all. What are you trying to achieve? Are you sure you want to call this.each()?
Like the others said, jQuery returns jQuery objects in most cases, and accessing the actual object can be accomplished using an indexer [] or the get method.

Categories

Resources