I want to print a list (var lst=[1,2,3,4,5]) using a loop on the same line. Can I do that in JavaScript ?
Well you can achieve this by doing this. Make an empty string variable and then concatenate each array value to it, then print it out. This will work
var lst = [1,2,3,4,5];
var output = "";
for(var i =0; i <= lst.length; i++){
output += lst[i] + " ";
}
console.log(output);
In NodeJS and as long as you didn't change your standard output you can use process.stdout.write("Something here") as the standard output of your application is terminal (console).
process.stdout.write("Hello ")
process.stdout.write("World")
process.stdout.write("!")
Hello world!
Console.log doesn't allow you to print in the same line. However the task that you are trying to do can be done using the below:
console.log(lst.join(" "))
Output: 1 2 3 4 5
You could use Function#apply or spread syntax ....
var list = [1, 2, 3, 4, 5];
console.log.apply(null, list); // traditional
console.log(...list); // ES6
The exact behavior of console.log is not specified by ECMAScript, so it varies from implementation to implementation, but it is intended to be used for logging events. The fact that each event usually becomes a single line in a web browser's console window led it to be the Node.js equivalent of "println", but outside the context of a specific implementation its behavior is not predictable.
You can pass multiple parameters to log, in which case most (but not all) implementations will print them all out on the same line separated by whitespace. So if you're using one of those implementations, and you have a list and just want all the elements on one line separated by space, you can use apply to call the method as if each element of the list was a separate argument:
console.log.apply(console, lst);
Caveat: if the first argument is a string that contains what look like Formatter format control sequences (%s, etc.), it will be parsed as such and the remaining arguments used to fill in those slots.
But the most reliable way to achieve the desired result is to build a single string yourself representing what you want the final line to look like, and then call console.log exactly once with that string as the argument.
You could do it easily by using the join() function which can be used on any array in JavaScript!
For example:
var lst = ["check","word","3","could","hello"]
console.log(lst.join())
source-code:
https://jsfiddle.net/Lpdurxsb/
Related
Just started using indexOf() and lastIndexOf() functions and I know why they are used, however, the result doesn't make me feel happy :)
let str = $('#info').html();
// WORKS
//alert(str.lastIndexOf('√'));
// DOESN'T WORK
alert(str.lastIndexOf('√'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="info">√</div>
The problem is I get the alert result as "-1", which means the √ couldn't be found in the str variable. Using simple symbol √ it works, however, I'm not sure if it's a good practice using this symbol here.
In my opinion, another approach about this problem would be encoding √ symbol in the HTML to √, so using "Inspect element" feature you would see √.
What do you think?
There is no direct way to achieve this. But if you still want to do this way then you simply need to create a HEX value of the ASCII value:
let str = ascii_to_hexa($('#info').html());
str = '�'+str.toUpperCase()+';';
alert(str.lastIndexOf('√'));
function ascii_to_hexa(str)
{
var arr1 = [];
for (var n = 0, l = str.length; n < l; n ++){
var hex = Number(str.charCodeAt(n)).toString(16);
arr1.push(hex);
}
return arr1.join('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="info">√</div>
When the browser reads and parses your HTML, it builds up a DOM, without retaining the exact HTML you provided. Later, if you ask for HTML, it builds a new HTML string using its own rules for doing that.
That's why str.lastIndexOf('√') doesn't work: The browser isn't under any obligation to give you back the character in the same form you used when you supplied it. It could give it back as just a character (√) or a named character reference (√ in this case) or a decimal numeric character reference (√), rather than the hex numeric character reference you're looking for.
You'll have to test on your target browsers to see what they give you, and then look for that. I suspect most if not all will return the actual character, and so your str.lastIndexOf('√') (or str.lastIndexOf('\u221A')) will be the way to go.
<div>√</div>
I have a group of strings in Javascript and I need to write a function that detects if another specific string belongs to this group or not.
What is the fastest way to achieve this? Is it alright to put the group of values into an array, and then write a function that searches through the array?
I think if I keep the values sorted and do a binary search, it should work fast enough. Or is there some other smart way of doing this, which can work faster?
Use a hash table, and do this:
// Initialise the set
mySet = {};
// Add to the set
mySet["some string value"] = true;
...
// Test if a value is in the set:
if (testValue in mySet) {
alert(testValue + " is in the set");
} else {
alert(testValue + " is not in the set");
}
You can use an object like so:
// prepare a mock-up object
setOfValues = {};
for (var i = 0; i < 100; i++)
setOfValues["example value " + i] = true;
// check for existence
if (setOfValues["example value 99"]); // true
if (setOfValues["example value 101"]); // undefined, essentially: false
This takes advantage of the fact that objects are implemented as associative arrays. How fast that is depends on your data and the JavaScript engine implementation, but you can do some performance testing easily to compare against other variants of doing it.
If a value can occur more than once in your set and the "how often" is important to you, you can also use an incrementing number in place of the boolean I used for my example.
A comment to the above mentioned hash solutions.
Actually the {} creates an object (also mentioned above) which can lead to some side-effects.
One of them is that your "hash" is already pre-populated with the default object methods.
So "toString" in setOfValues will be true (at least in Firefox).
You can prepend another character e.g. "." to your strings to work around this problem or use the Hash object provided by the "prototype" library.
Stumbled across this and realized the answers are out of date. In this day and age, you should not be implementing sets using hashtables except in corner cases. You should use sets.
For example:
> let set = new Set();
> set.add('red')
> set.has('red')
true
> set.delete('red')
true
> set.has('red')
false
Refer to this SO post for more examples and discussion: Ways to create a Set in JavaScript?
A possible way, particularly efficient if the set is immutable, but is still usable with a variable set:
var haystack = "monday tuesday wednesday thursday friday saturday sunday";
var needle = "Friday";
if (haystack.indexOf(needle.toLowerCase()) >= 0) alert("Found!");
Of course, you might need to change the separator depending on the strings you have to put there...
A more robust variant can include bounds to ensure neither "day wed" nor "day" can match positively:
var haystack = "!monday!tuesday!wednesday!thursday!friday!saturday!sunday!";
var needle = "Friday";
if (haystack.indexOf('!' + needle.toLowerCase() + '!') >= 0) alert("Found!");
Might be not needed if the input is sure (eg. out of database, etc.).
I used that in a Greasemonkey script, with the advantage of using the haystack directly out of GM's storage.
Using a hash table might be a quicker option.
Whatever option you go for its definitely worth testing out its performance against the alternatives you consider.
Depends on how much values there are.
If there are a few values (less than 10 to 50), searching through the array may be ok. A hash table might be overkill.
If you have lots of values, a hash table is the best option. It requires less work than sorting the values and doing a binary search.
I know it is an old post. But to detect if a value is in a set of values we can manipulate through array indexOf() which searches and detects the present of the value
var myString="this is my large string set";
var myStr=myString.split(' ');
console.log('myStr contains "my" = '+ (myStr.indexOf('my')>=0));
console.log('myStr contains "your" = '+ (myStr.indexOf('your')>=0));
console.log('integer example : [1, 2, 5, 3] contains 5 = '+ ([1, 2, 5, 3].indexOf(5)>=0));
You can use ES6 includes.
var string = "The quick brown fox jumps over the lazy dog.",
substring = "lazy dog";
console.log(string.includes(substring));
I am looking at the source of pace.js and it has a pretty long source code of about a thousand lines. You can view the source here.
I need to debug this code. Is there any tool or method in JavaScript using which one can identify how many unique functions are there in a given plugin? I found one way which is:
Paste the code in a text editor
Identify each function individually
Paste a console.log("i am so and so function").
Run the script and copy paste the result from the console in a text editor
Count the number of functions
Is there a easier way to do this?
This approach first finds all the functions in the window object. Then passes those function references to 'getInnerFunction()' which matches the function against a regular expression to detect any inner functions. Finally the count of functions is returned.
However it will not be able to detect inner functions of native function present in the browser, since they return
function FUNCTION NAME {
[native code]
}
this as the to string output.
For other cases this should work. Just call fnCount() and you will receive the number of functions present (subtract 2 from the result to exclude these 2 functions).
** Please correct me if there is any problem with the function matching regular expression.
function fnCount(){
var keys = Object.keys(window);
var property;
var count = 0;
for(var i=0;i<keys.length; i++){
property = window[keys[i]];
if(typeof(property) === 'function'){
count += getInnerFunction(property);
}
}
return count;
}
function getInnerFunction(property){
var fn = property.toString();
var fnCount = fn.match(/function.*\(.*\).*{.*/g).length;
return fnCount;
}
Open notepad++, press CTRL+F, type function, click Find all...
Goal
I have a working function (JSFiddle). On numerous occasions throughout a script the function runs sequentially. In these instances, there is a lot of repetitious code that I would like to consolidate.
Ideally changing code like this:
functionName("First_item") +
functionName("Second_item") +
functionName("Third_item") +
To something like this:
functionName("First_item", "Second_item", "Third_item");
The function will run for each item in the list so the result is the same but the code more elegant and maintainable.
Notes:
I’m not looking to use any libraries (e.g. jQuery) to accomplish the goal.
Solution
Amit Joki’s answer kindly noted I could use arguments. When I implemented the code, the modified function (JSFiddle) only returned the output string for the first argument / item.
Vanice’s answer pointed out the eventual solution.
Make one string from the output of all arguments / items by concatenating (joining) the output strings within the for loop (with the use of +=).
Return the concatenated output by placing the return outside of the for loop.
Example
Working solution (JSFiddle).
Thanks
Thank you very much to everyone for their time and help on this. I really appreciate it!
Leveraging Javascript's Prototype OOP: You can add an each function to Array's themselves, so every array in your code that will automatically have an inhereted each function.
Array.prototype.each = function(callback){
for (var i = 0; i < this.length; i++){
callback(this[i]);
}
}
Usage:
myArray.each(myCoolFunction)
['something','somethingelse',somethingother'].each(myCoolFunction)
myArray.each( function (item) {
// if your item has a method
item.Something();
// if you'd like to call a function on the item:
doSomething(item);
});
caveats:
Because javascript is an asynchronous language that is interpreted differently across various browsers and inherently handles primitive objects and complex objects differently, it is highly recommended usage of underscore or lodash. You can also make your own, but you'll need ensure the objects passed through will be handled by the functions properly. This may include workarounds or creating special callback functions for different object types that are passed through your each function.
For more information: Is JavaScript a pass-by-reference or pass-by-value language?
Libraries you should seriously consider:
lodash:
https://lodash.com/docs#forEach
_([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
// → logs each number and returns '1,2,3'
_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
// → logs each number and returns the object (property order is not guaranteed across environments)
underscore:
http://underscorejs.org/#each
_.each([1, 2, 3], alert);
=> alerts each number in turn...
You don't need an array. Just use arguments
function functionName(){
for(var i = 0; i < arguments.length; i++){
// do something with arguments[i];
}
}
and then you can do
functionName("shot_type","shot_height","shot_angle","framed","scene_depth");
P.S #codebox's solution works if supporting legacy IE version isn't a problem. Don't know why he deleted it...so putting it here so it helps. His answer using forEach
["shot_type","shot_height","shot_angle","framed","scene_depth"].forEach(FunctionName);
EDIT: Looking at your Fiddle, you have a return inside the for loop - therefore the function will return after the first iteration. Put the return after the for and concatenate the output to one string.
var output = "";
for(...){
output += description_of_object + ": " + randomly_selected_item_from_object + ".\n";
}
// return it
return output;
With Javascript only:
var actions = ["shot_type","shot_height","shot_angle","framed","scene_depth"];
for (var i = 0; i < actions.length; i++){
FunctionName(actions[i]);
}
With JQuery:
$.each(["shot_type","shot_height","shot_angle","framed","scene_depth"], function(index,value){
FunctionName(value);
});
I haven't tested it but it should work.
To avoide redundancy in code use an array with the values, that you want to pass through the function and call the function in an loop.
var vals=["shot_type","shot_height","shot_angle","framed","scene_depth"];
for(var i=0; i<vals.length; i++)
{
FunctionName(vals[i]);
}
If you want to expand the function (adding another parameter) you can just expand the for-loop and the array structure.
Alternatively you could fill an object with the values and handle this logic in an object. But this would just do a difference on calling the function.
I have seen commas to concatenate primitive data types in Javascript and was wondering whether there was any difference in using a comma over say the + operator as well as the .concat() function?
So an example the following statement gives me abc
var value1 = a, value2 = b, value3 = c;
document.write(value1,value2,value3);
Apples and oranges. Nothing is being concatenated in your example; you are simply specifying 3 arguments to the write() function.
document.write(exp1, exp2, exp3, ...) accepts multiple parameters, and when given multiple parameters it will iterate through them all as if you called write() on each one individually.
However, the comma does have a use when evaluating expressions where it is used to process multiple expressions and returns the last one. To see that in action you need to wrap your parameters in a set of parenthesis so that it forms a single parameter:
document.write("a","b","c") // abc
document.write( ("a", "b", "c") ) // c
alert("a","b","c") // a
alert( ("a","b","c") ) // c
alert( (x=2, ++x) ) // 3
Since string concatenation is one of the haviest operations on computing, using document.write with various parameters would perform better.
See this test (it sometimes hangs in IE, so use other browser please) http://jsperf.com/document-write-vs-concatenation
Explaination:
document.write("val1", "val2", "val3");
is equivalent to
document.write("val1");
document.write("val2");
document.write("val3");
Thus, being much faster, since it doesn't concatenates the strings.
In most browsers (IE <= 8, Gecko) string concatenation using the + operator has horrible performance.
In my company, for example, we have to compose a large HTML fragment piece by piece. In this case we have something like this:
var id = 123;
var html = [];
html.push('<div id="', id, '">hello</div>');
var result = html.join('');
In the case where you have LOTS of concatenations, this is MUCH better than the following:
var id = 123;
result = '<div id="' + id + '">hello</div>';
So to answer your question - it really depends on the situation. If you are concatenating many strings together you should never use the + operator due to poor performance. But it should be fine 99% of the time where the performance gain will be so little it is just painful to try anything else. But in cases where you actually have the option to comma separate (like in the case of array.push, or document.write) then you should definately take advantage of it.