Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Below is a piece of working code. The "= true" part is confusing to me. This is what I think is happening.
1- create empty array.
2- take the selected list items (targets) and loop.
3- if the class attributes for the target list item is not in the array then enter if block.
4- add the class attributes for the target list item and add them
to the array.
My understanding is that javascript uses "push" and jquery uses "add" to
insert items into an array. The code below does not use push or add.
var foo = [];
$($targets).each(function(i) {
if (!foo[$(this).attr('class')]) {
foo[$(this).attr('class')] = true;
}
});
The code is flawed, you'd use an object instead of an array if you want to use strings as keys:
var foo = {};
Then it checks if the key is falsy in the object, although you may want to check for strict existence with the in operator:
$targets.each(function() {
var klass = this.className; // cache, no need for jQuery
// if `foo` doesn't have the key `klass` then add it
if (! (klass in foo)) foo[klass] = true;
});
Unless the class names are numbers like "1" or "2", you can't access items inside the array that way. That said, arrays are built from objects. So for example you can do things like this:
var foo = ['a', 'b', 'c'];
foo.bar = 'hello';
foo;
//=> ['a', 'b', 'c']
foo[0];
//=> 'a';
foo['bar'];
//=> 'hello';
So what's happening is that your script is not adding those items into the actual array. Instead, it's assigning them to the array as if it was a regular JavaScript object.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 11 months ago.
Improve this question
Let's say I have this function in JavaScript:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
b = foo(b)
console.log(b)
Since JavaScript is a call-by-sharing language there is no need to return a, the object b would have the same final value with the below code:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
foo(b)
console.log(b)
Is it bad practice to use return b for better readability even though it is not needed
Are there any downsides to returning the object?
You're correct, in your example the return statement is unnecessary, strictly speaking. Also, just as a point of clarification, while JS passes objects by reference, primitive types are passed by value.
However, it is considered a JS best practice to avoid mutating function parameters. It can very quickly get very confusing when you have many functions performing actions on the same object that is getting passed around and mutated. So, in fact, I would consider it a bad practice to write a mutating function that does not involve returning a value.
Following that idea, your example would look like:
function foo(a) {
// Copy our input (assuming 'a' only contains primitive values)
const output = { ...a };
output.item = 'four';
return output;
}
const b = { item: 'three' };
const c = foo(b);
// b is unchanged
The built-in Array.prototype.sort() method returns the array even though it's sorting it in place.
Whether this provides better readability is a matter of personal preference. But it can make it easier to work with arrays/objects that are created on the fly, e.g.
sorted_words = string.split(" ").sort();
If it didn't return the array, you'd have to do this in two steps:
sorted_words = string.split(" ")
sorted_words.sort();
This question already has answers here:
Dynamically set property of nested object
(28 answers)
Closed 5 years ago.
Say you have this object:
myObj = { foo: { bar : 123, baz: 456 } };
To edit the value of bar you can do this:
myObj['foo']['bar'] = 789
But what if you have a method somewhere that changes specific object properties like this:
myObj[key] = value
If you need to use that and you want to edit bar in the myObj object, is it possible with that code?
I tried:
myObj["foo"."bar"] = 789;
myObj["foo"["bar"]] = 789;
But it doesn't work. Is it possible at all to do?
Pure JavaScript doesn't allow you to access nested properties with a simple string.
An alterative can be i.e. lodash:
_.get(myObj, 'foo.bar'); // 123
_.set(myObj, 'foo.bar', 789);
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
For example I have to add 'foo' to string.
So I have at least two ways to go.
First, I can implement String.prototype.foo:
String.prototype.foo = function() {
return this + 'foo';
};
var s = 'str';
var data = s.foo(); // "strfoo"
Another way:
function foo(str) {
return str + 'foo';
}
var s = 'str';
var data = foo(s); // "strfoo"
Both look pretty. But should I think about any "underwater rocks" before choosing first or second implementation? Are there any significant reasons, such as efficiency and performance?
The first extend the functionalities of String.
Use this solution if you have a class of objects and you like to add new behaviours to it.
The second is more an utility function.
Note also that you can apply the second foo also to a variable that is not a String, so you should also test the type of the argument if you like to limit the use to a String argument.
Modifying the globals in JavaScript is always a bad decision. Don't do that, except if it's not about making a polyfill.
The implications are multiple from your code being not portable to probability of breaking someone else's code.
I would always use the second method. Or if things are really that complicated maybe implement my own class of String.
function MyString(str) {
this.str = str;
}
MyString.prototype.foo = function() { return this.str + "foo" };
var s = new MyString("str");
var data = s.foo(); // "strfoo"
Here is further reading about modifying global objects and the downsides :
https://softwareengineering.stackexchange.com/questions/104320/why-is-extending-the-dom-built-in-object-prototypes-a-bad-idea
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In javascript, we can initialise a variable with {}. What does the "{}" mean?
var o = {};
o.getMessage = function ()
{
return 'This is an example';
};
return o;
This means you create an object with a variable
Its known as object with literal notation.which seems like below .
var o = {}
here your object has no property or it can be say as empty literal block .But in the below code
var o = {
o .first= 20;
o .second= 10;
o.result =function(){
return this . first- this .second;
}
} ;
now you have your object with property and function
** though there are several ways of creating object But Literal notation is the easiest and popular way to create objects
Basically the different cases are:
Use {} instead of new Object()
Use "" instead of new String()
Use 0 instead of new Number()
Use false instead of new Boolean()
Use [] instead of new Array()
Use /()/ instead of new RegExp()
Use function (){} instead of new Function()
Basically, it is an empty object. When you add the getMessage() function at the bottom of the variable, you actually added it to the empty object, resulting to your empty object now to look like this:
var o = {
getMessage: function() {
return 'This is an example';
}
};
You can create a scope or class with it, in which you can use closures to keep certain variables private within that scope.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to parse an array from one function ton another.
I have seen in other posts that ".apply" can be used as in this example:
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
But in my code I want to parse to other function not just one array, I want to parse the array and two strings more. So mi code looks more like:
var array = [1, 2, 3];
var string = "something":
var string1 = "something":
ShowM(array, string, string2);
function ShowM(array, string1, string2) {
alert(array[1] + string1 + string2);
}
Is there any way to do that without changing the original location of the elements of the arrays for not getting undefined?. Thnks
If the question is purely about how do you set an array as a parameter in Javascript as your topic question states, you just do like any other variable.
var array = [a,b,c];
var str = "hello";
var str2 = "something";
function foo(x,y,z) {
// do stuff...
}
foo(array, str, str2); //executes function with the 3 parameters
If you just want to pass the array into a function, you can pass it as you would any other variable:
function showM(a, b, c) {
// empty function definition
}
var x = [ 'p0', 'p1', 'p2' ];
showM(x, "some string", "another string");
All arrays are passed by reference in javascript, so when you alter a passed array's contents within the function, the contents will change across all scopes. And duck-typing means that you can use any variable type as an argument.
The apply function, on the other hand, calls a function with a given content and an array of arguments (which it expands, like with the ES6 spread operator):
// equivalent to the other call, except "this" is bound to null
showM.apply(null, [x, "some string", "another string"]);